Node.js, multer and req.body empty
I resolve moving req.body
at the end of the post function:
app.post('/api/upload?:test',function(req,res){
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
console.log(req.body);
});
});
If someone can tell me why I will happy to learn a new thing! But, for now, I resolved!
You need to re-arrange the fields from frontend request, Below i will explain,
I am using multer to upload multiple files and single file in my nodejs application.
Postman request screenshot (Mistaked):
Postman request screenshot (correct method):
See the difference in order of fields. Always attach media files in last of the req content.
I had spent a 2 hours nearly to find this. Definitly Work. Just try it.
Move your console.log(req.body)
inside upload(req,res,function(err) {...})
The default express body-parser cannot work with multipart/form-data, hence we use multer to parse form-data which is accessible inside your upload function.
2017 Update
From Readme
Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.
I resolved my issue by reversing the order of my form object properties in the front end:
var newFormObj = new FormData();
newFormObj.append('internalUserID', internalUserID);
newFormObj.append('listingImage', this.binaryImages[image]);
On the backend:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
console.log(req.body.internalUserID) // YAY, IT'S POPULATED
cb(null, 'listing-pics/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({ storage: storage });