I'm sending an FormData
from a VueJS
application using Axios
. The problem is that when I output the FormData
it's empty. I've used the same method before when sending a file (I'm not sending a file now) and then the FormData
shows the right data that I've append to it. The data I'm appending is of the type string.
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);
});
});
From axios documentation:
By default, axios serializes JavaScript objects to JSON.
So, you can't just pass a JS FormData
object straight to the options of an axios
call. If you must use FormData
, see recommended methods here: https://www.npmjs.com/package/axios#using-applicationx-www-form-urlencoded-format
However, if, as you mention above, but what looks like key/value pairs, don't use FormData
at all, but a regular JavaScript Object.
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, ...