Reputation: 339
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);
});
});
Upvotes: 3
Views: 15933
Reputation: 1
I had the same problem using axios in express (don't know if that matters). The body of the request sent remained empty. What helped in my case was to update Axios to the latest version, from 0.27.2
to 1.5.1
.
Upvotes: 0
Reputation: 1
Starting from v0.27.0, Axios supports automatic object serialization to a FormData object if the request Content-Type header is set to multipart/form-data. see the documentation!
Upvotes: 0
Reputation: 5455
Aren't you supposed to use .set() not .append() for regular fields, I thought you used .append() for files only?
I also suggest getting to grips with native JSON for form data handling as the other answer mentions, It is a lot simpler, cleaner solution.
Upvotes: 2
Reputation: 3515
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, ...
Upvotes: 5