使用Axios发送后,表单数据为空

时间:2018-11-20 20:49:29

标签: node.js express vue.js axios multipartform-data

我正在使用FormDataVueJS应用程序发送Axios。问题是当我输出FormData时它是空的。发送文件之前,我已经使用了相同的方法(我现在不发送文件),然后FormData显示了正确的数据,这些数据已经附加到文件中。我要附加的数据是字符串类型。

  

客户端

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);
    });
  }
  

服务器端

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);
    });
});

2 个答案:

答案 0 :(得分:2)

来自axios文档:

  

默认情况下,axios将JavaScript对象序列化为JSON。

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

但是,如上所述,如果看起来像键/值对,则根本不用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, ... 

答案 1 :(得分:1)

您不应该对常规字段使用 .set()而不是.append()吗?我以为您仅将.append()用于文件?

我还建议像其他答案中提到的那样,使用本机JSON处理表单数据,这是一个更简单,更简洁的解决方案。