我正在使用 Axios
从 VueJS
应用程序发送 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
但是,如果正如您上面提到的,但看起来像键/值对,则根本不要使用 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, ...
关于node.js - 用axios发送后表单数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53401293/