当状态为 200 ok 时,axios 发送网络错误

har*_*ool 3 node.js express axios vuejs2

我正在使用以下 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);
}); 
Run Code Online (Sandbox Code Playgroud)

图片现在在服务器上,但是,请看一下我在 Firefox 控制台中看到的奇怪行为,它显示“网络错误”,而 Axios 正在接收 200 状态!:

问题

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

Error: "Network Error"
    createError createError.js:16
    handleError xhr.js:81
Run Code Online (Sandbox Code Playgroud)

这是我的 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();
});
Run Code Online (Sandbox Code Playgroud)

这是一个大问题,因为我需要能够利用 .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);
});
Run Code Online (Sandbox Code Playgroud)

编辑将我的节点服务器端口更改为 3000:问题仍然相同:

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

Error: "Network Error"
    createError createError.js:16
    handleError xhr.js:81
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到结果答案?

我需要获取重命名的图片,但无法访问 .then() axios 函数。

请看那里: 在此输入图像描述

我无法在 axios .then() 内获取 nico.jpg-5454545 ,它总是显示“网络错误”

编辑 3: 更改了我的后端参数,但没有运气:(这是 webpack 应用程序端口)

res.header("Access-Control-Allow-Origin", "http://localhost:8081");
Run Code Online (Sandbox Code Playgroud)

编辑4: 像这样更改了我的axios查询,但没有运气(这是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
                   }

                }); 
        },
Run Code Online (Sandbox Code Playgroud)

编辑5:

尝试这段代码没有运气,我需要访问响应数据,并且只得到“网络错误”

 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);
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我正在尝试切换到 vue-resource,我真的足够了!

编辑6:看起来这仍然是一个CORS问题:

在此输入图像描述

编辑7:已解决!

问题是我的整个 CORS 代码位于我的 app.post("/images" ... function inside my app.js on the node.js server 。换句话说,cors 代码需要保留在顶部app.js node.js 服务器文件。

现在这是我的 CORS 代码,请注意,它现在位于图像 Web 服务之前:

// ----------------------------------- 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);
}); 
Run Code Online (Sandbox Code Playgroud)

它现在工作完美,不再出现网络错误,我的文件名正确! 在此输入图像描述

har*_*ool 5

编辑7:已解决!

问题是我的整个 CORS 代码是在 Node.js 服务器上的 app.js 内的 app.post("/images" ... 函数下编写的。换句话说,cors 代码需要保留在顶部app.js node.js 服务器文件的。

现在这是我的 CORS 代码,请注意,它现在位于图像 Web 服务之前:

// ----------------------------------- 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);
}); 
Run Code Online (Sandbox Code Playgroud)

它现在工作完美,不再出现网络错误,并且我的文件名正确! 在此输入图像描述