Node.js, multer and req.body empty

Here is my problem, I have a form where I can insert a file and field, but I only get the file, not the test parameter! Why?

This is my code:

app.js:

 var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var port = 8000; var multer = require('multer'); // v1.0.5 var storage =  multer.diskStorage({ destination: function (req, file, callback) {  callback(null, './uploads'); }, filename: function (req, file, callback) {  callback(null, file.originalname.substring(0,file.originalname.lastIndexOf('.')) + '-' + Date.now() + file.originalname.substring(file.originalname.lastIndexOf('.'),file.originalname.length)); } }); var upload = multer({ storage : storage}).single('fileUpload'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); app.post('/api/upload',function(req,res){ console.log(req.body);  upload(req,res,function(err) {    if(err) {      return res.end("Error uploading file.");    }    res.end("File is uploaded");  }); }); app.listen(port, function () { console.log('Express server inizializzato sulla porta ' + port); }); 

index.html

 <html> <head> <title>Test upload</title> </head> <body> <form name="form" action="http://localhost:8000/api/upload" method="post" enctype="multipart/form-data"> <input type="text" name="test" /> <input type="file" name="fileUpload" /> <input type="submit" value="invia" /> </form> </body> </html> 

Can anybody help me?

+6
source share
2 answers

Update 2017

From Readme

Note that req.body may not have been completely populated yet. It depends on the client transferring the fields and files to the server.

I solved the problem by changing the order of my properties of the form object in the interface:

  var newFormObj = new FormData(); newFormObj.append('internalUserID', internalUserID); newFormObj.append('listingImage', this.binaryImages[image]); 

On server:

 var storage = multer.diskStorage({ destination: function (req, file, cb) { console.log(req.body.internalUserID) // YAY, IT POPULATED cb(null, 'listing-pics/') }, filename: function (req, file, cb) { cb(null, file.fieldname + '-' + Date.now()) } }); var upload = multer({ storage: storage }); 
+6
source

I allow req.body to be moved 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 tells me why I will be happy to learn new things! But at the moment I decided!

+3
source

All Articles