用axios发送后表单数据为空

Form data is empty after sending it with Axios

我正在使用 AxiosVueJS 应用程序发送 FormData。问题是当我输出 FormData 时它是空的。我以前在发送文件时使用过相同的方法(我现在不发送文件)然后 FormData 显示我附加到它的正确数据。我附加的数据是字符串类型。

Client Side

onUpload(): void {
      const fd = new FormData();
      fd.append("id", this.chosenRoute.id);
      fd.append("name", this.routeName);
      fd.append("description", this.routeDescription);
      fd.append("activity", this.activity);
      fd.append("preamble", this.preamble);
      axios.post('http://localhost:8080/editRoute', fd, {
      onUploadProgress: uploadEvent => {
        console.log('Upload Progress' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " %");
      }
    }).then(
      res => {
      console.log(res);
    });
  }

Server Side

app.post('/editRoute', function(req,res){
    console.log(req.body);
    const routeId = req.body.id;
    console.log(routeId);
    Route.findById(routeId, (err, route) => {
        res.set("Access-Control-Allow-Origin", "*");
        route.update(req.body);
    });
});

来自 axios 文档:

By default, axios serializes JavaScript objects to JSON.

因此,您不能直接将 JS FormData 对象传递给 axios 调用的选项。如果您必须使用 FormData,请参阅此处推荐的方法:https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format

然而,如果,正如你上面提到的,但是看起来像 key/value 对,根本不要使用 FormData,而是一个常规的 JavaScript 对象。

const body = {
    "id": this.chosenRoute.id.
    "name": this.routeName,
    "description": this.routeDescription,
    "activity": this.activity,
    "preamble": this.preamble
}

axios.post('http://localhost:8080/editRoute', body, ... 

你不是应该对常规字段使用 .set() 而不是 .append() 吗,我以为你只对文件使用 .append() ?

我还建议掌握本机 JSON 以处理表单数据,正如其他答案提到的那样,这是更简单、更清晰的解决方案。