programing

상태가 200 OK인 동안 Axios가 네트워크 오류를 전송함

prostudy 2022. 7. 28. 20:11
반응형

상태가 200 OK인 동안 Axios가 네트워크 오류를 전송함

node.js express 서버에 다음 액시오 쿼리를 사용하여 이미지를 보냅니다.

axios.post(this.server + 'images',
    formData, {
        crossdomain: true,
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }
).then(function (result) {
    console.log(result);
})
.catch(function (error) {
    console.log(error);
}); 

그림은 현재 서버상에 있지만, Firefox 콘솔 내부에서 보이는 이상한 동작을 보세요.Axios가 200의 상태를 수신하고 있는 동안 '네트워크 에러'라고 표시되어 있습니다.

문제

POST http://localhost/images
[HTTP/1.1 200 OK 20ms]

Error: "Network Error"
    createError createError.js:16
    handleError xhr.js:81

이것은 my node.js 백엔드 Cors 파라미터입니다.

const cors = require("cors");
app.use(
  require("cors")({
    origin: function(origin, callback) {
      callback(null, origin);
    }
  })
);
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", req.headers.origin); // update to match the domain you will make the request from
  //to allow cross domain requests to send cookie information.
  res.header("Access-Control-Allow-Credentials", true);
  // list of methods that are supported by the server
  res.header("Access-Control-Allow-Methods", "OPTIONS,GET,PUT,POST,DELETE");

  res.header(
    "Access-Control-Allow-Headers",
    "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, X-XSRF-TOKEN"
  );

  next();
});

.then() 응답을 악용할 수 있어야 하는데 이용할 수 없기 때문에 이것은 큰 문제입니다.

또 뭘 해야 하죠?

  • 노드 서버는 localhost:80 에서 기동합니다.
  • Webpack-vue.js 앱은 localhost:8080에서 기동됩니다.

메모: 이것은 사진을 얻기 위한 노드 기능입니다.사진 업로드 후 200 상태를 보냅니다.

app.post("/images", upload.single("file"), function(req, res, next) {
sharp(req.file.path)
    .resize(200, 200)
    .toBuffer(function(err, buffer) {
      fs.writeFile(req.file.path, buffer, function(e) {});
    });

  res.sendStatus(200);
});

EDIT my node server port를 3000으로 변경 : 문제는 그대로입니다.

POST http://localhost:3000/images
[HTTP/1.1 200 OK 11ms]

Error: "Network Error"
    createError createError.js:16
    handleError xhr.js:81

어떻게 하면 결과 답변을 얻을 수 있을까요?

이름이 바뀐 사진을 가져와야 하는데 .then() axios 함수에 접속할 수 없습니다.

여기를 봐주세요.

axios.then() 내에 nico.jpg-54545를 가져올 수 없습니다.항상 '네트워크 오류'라고 표시되어 있습니다.

EDIT 3 : 백엔드 파라미터를 변경했지만 운이 없었습니다 : (이것은 웹팩 앱 포트입니다)

res.header("Access-Control-Allow-Origin", "http://localhost:8081");

EDIT 4 : 다음과 같이 액ios 쿼리를 변경했지만 실패하였습니다(이것은 node.js 서버 포트입니다).

axios.post(this.server + 'images',
                    formData, {
                      crossdomain: true,
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            'Access-Control-Allow-Origin': "http://localhost:3000"
                        }
                    }
                ).then(function (e) {
                     if (e){
                    console.log(e);
                   }
                })
               .catch(function (err ) {
                   if (err.message === "Network Error"){
                    console.log(err); // Works but nothing gets shown
                   }

                }); 
        },

편집 5:

이 코드를 시도했지만 성공하지 못했습니다. 응답 데이터에 액세스해야 하는데 'NETWORK ERROR'만 표시됩니다.

 const send = async () => {
            try {
                return await  axios.post(this.server + 'images',
                    formData, {
                      crossdomain: true,
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        }
                    }
                )
            } catch (error) {
                console.error(error)
            }
            }

            const myFilename = send()
            console.log(myFilename);

여기에 이미지 설명 입력

vue-resource로 전환하려고 합니다. 정말 충분합니다!

Edit 6 : 아직 CORS 문제인 것 같습니다.

여기에 이미지 설명 입력

편집 7 : 해결 완료!!

문제는 CORS 코드 전체가 node.display 서버의 application.displays 내의 app.post/displays" ...기능 아래에 있다는 것입니다.즉, cors 코드는 app.js node.js 서버 파일의 맨 위에 있어야 합니다.

이것은 현재 제 CORS 코드입니다.주의하세요.이미지 웹 서비스 전입니다.

// ----------------------------------- CORS -------------------------------------------

const cors = require("cors");
app.use(require("cors")());

app.use(
  cors({
    origin: ["http://localhost:8081", "http://localhost:8081/images"],
    credentials: true
  })
);

// ----------------------------------- END OF CORS -------------------------------------------

app.post("/images", upload.single("file"), function(req, res, next) {
  console.log(req.file);

  sharp(req.file.path)
    .resize(200, 200)
    .toBuffer(function(err, buffer) {
      fs.writeFile(req.file.path, buffer, function(e) {});
    });
  res.send({ filename: req.file.filename });
  // res.sendStatus(200);
}); 

지금은 완벽하게 동작하고 있습니다.네트워크 에러는 없고, 파일명도 올바르게 취득하고 있습니다!!여기에 이미지 설명 입력

편집 7 : 해결 완료!!

문제는 CORS 코드 전체가 node.disp 서버의 application.disp에 있는 "app.post"/disp"... 함수로 작성되어 있다는 것입니다.즉, cors 코드는 app.js node.js 서버 파일의 맨 위에 있어야 합니다.

이것은 현재 제 CORS 코드입니다.주의하세요.이미지 웹 서비스 전입니다.

// ----------------------------------- CORS -------------------------------------------

const cors = require("cors");
app.use(require("cors")());

app.use(
  cors({
    origin: ["http://localhost:8081", "http://localhost:8081/images"],
    credentials: true
  })
);

// ----------------------------------- END OF CORS -------------------------------------------

app.post("/images", upload.single("file"), function(req, res, next) {
  console.log(req.file);

  sharp(req.file.path)
    .resize(200, 200)
    .toBuffer(function(err, buffer) {
      fs.writeFile(req.file.path, buffer, function(e) {});
    });
  res.send({ filename: req.file.filename });
  // res.sendStatus(200);
}); 

지금은 완벽하게 동작하고 있습니다.네트워크 에러는 없어졌습니다.파일명은 올바르게 취득하고 있습니다!!여기에 이미지 설명 입력

언급URL : https://stackoverflow.com/questions/58717673/axios-sending-network-error-while-status-is-200-ok

반응형