How to access Express 4 req.body object using Busboy

I need an easy way to access multi-page form data in a req object using busboy-connect. I am using Express 4, which now needs modules for previously built-in functions.

I want the req.body object to be accessible on my routes, but the busboy.on ('field') function is asynchronous and does not process all form data before passing it to continue working on the code.

There is a middleware module built on the top of the bus called multer that receives the req.body object before it enters the route, however it overrides the ability to determine the busboy.on ('file') event from the route.

Here is my broken code:

// App.js app.post(/users, function(req, res, next){ var busboy = new Busboy({ headers: req.headers }); // handle text field data (code taken from multer.js) busboy.on('field', function(fieldname, val, valTruncated, keyTruncated) { if (req.body.hasOwnProperty(fieldname)) { if (Array.isArray(req.body[fieldname])) { req.body[fieldname].push(val); } else { req.body[fieldname] = [req.body[fieldname], val]; } } else { req.body[fieldname] = val; console.log(req.body); } }); busboy.on('file', function(fieldname, file, filename, encoding, mimetype) { tmpUploadPath = path.join(__dirname, "uploads/", filename); targetPath = path.join(__dirname, "userpics/", filename); self.imageName = filename; self.imageUrl = filename; file.pipe(fs.createWriteStream(tmpUploadPath)); }); req.pipe(busboy); // start piping the data. console.log(req.body) // outputs nothing, evaluated before busboy.on('field') // has completed. }); 

UPDATE I am using connect-busboy. I used this intermediate code in my express file to access the req.body object in my route. I can also handle uploading the file from my route and access req.busbuy.on ('end').

  // busboy middleware to grab req. post data for multipart submissions. app.use(busboy({ immediate: true })); app.use(function(req, res, next) { req.busboy.on('field', function(fieldname, val) { // console.log(fieldname, val); req.body[fieldname] = val; }); req.busboy.on('finish', function(){ next(); }); }); 
+7
multipartform-data express routes
source share
1 answer

Try adding:

 busboy.on('finish', function() { // use req.body }); 
+9
source share

All Articles