How to disable Express BodyParser to download files (Node.js)

It seems like this should be a pretty simple question, but it's very difficult for me to figure out how to approach it.

I use Node.js + Express to build a web application, and I find that the BodyParser connection that expresses seems to be very useful in most cases. However, I would like to have more detailed access to the multi-page POSTS of the form data, since they come - I need to transfer the input stream to another server and want to not download the whole file first.

However, since I use Express BodyParser, all file downloads are parsed automatically and downloaded and accessed using "request.files" before they ever get into any of my functions.

Is there a way to disable BodyParser for multipart formdata messages without disabling it for everything else?

+56
javascript file-upload express connect
Jul 02 2018-12-12T00:
source share
6 answers

When you type app.use(express.bodyParser()) almost every request will go through the bodyParser functions (which one will be executed depends on the Content-Type header).

By default, 3 headers are supported (AFAIR). You can make sure the sources are sure. You can (re) define handlers for the Content-Type with something like this:

 var express = require('express'); var bodyParser = express.bodyParser; // redefine handler for Content-Type: multipart/form-data bodyParser.parse('multipart/form-data') = function(req, options, next) { // parse request body your way; example of such action: // https://github.com/senchalabs/connect/blob/master/lib/middleware/multipart.js // for your needs it will probably be this: next(); } 

<h / "> UPD.

In Express 3, everything has changed, so I use the updated code from a working draft (should be app.use ed before express.bodyParser() ):

 var connectUtils = require('express/node_modules/connect/lib/utils'); /** * Parses body and puts it to `request.rawBody`. * @param {Array|String} contentTypes Value(s) of Content-Type header for which parser will be applied. * @return {Function} Express Middleware */ module.exports = function(contentTypes) { contentTypes = Array.isArray(contentTypes) ? contentTypes : [contentTypes]; return function (req, res, next) { if (req._body) return next(); req.body = req.body || {}; if (!connectUtils.hasBody(req)) return next(); if (-1 === contentTypes.indexOf(req.header('content-type'))) return next(); req.setEncoding('utf8'); // Reconsider this line! req._body = true; // Mark as parsed for other body parsers. req.rawBody = ''; req.on('data', function (chunk) { req.rawBody += chunk; }); req.on('end', next); }; }; 

And some pseudo code related to the original question:

 function disableParserForContentType(req, res, next) { if (req.contentType in options.contentTypes) { req._body = true; next(); } } 
+16
Jul 04 2018-12-12T00:
source share
— -

If you need to use the functions provided by express.bodyParser , but you want to disable it for multipart / form-data, the trick is to not use express.bodyParser directly . express.bodyParser is a convenience method that wraps three other methods: express.json , express.urlencoded and express.multipart .

Therefore instead of speaking

 app.use(express.bodyParser()) 

you just need to say

 app.use(express.json()) .use(express.urlencoded()) 

This gives you all the benefits of bodyparser for most data, allowing you to handle formdata loading on your own.

Edit: json and urlencoded are no longer associated with Express. They are provided by a separate body-parser module, and now you use them as follows:

 bodyParser = require("body-parser") app.use(bodyParser.json()) .use(bodyParser.urlencoded()) 
+59
Jul 02 2018-12-12T00:
source share

If the need for parsing the body depends only on the route itself, it is easiest to use bodyParser as a function of the route middleware only for the routes that it needs, and not for its use in the cover:

 var express=require('express'); var app=express.createServer(); app.post('/body', express.bodyParser(), function(req, res) { res.send(typeof(req.body), {'Content-Type': 'text/plain'}); }); app.post('/nobody', function(req, res) { res.send(typeof(req.body), {'Content-Type': 'text/plain'}); }); app.listen(2484); 
+27
Jul 04 2018-12-12T00: 00Z
source share

Inside Express 3, you can pass the parameter bodyParser as {defer: true} , which urgently defers multiprocessing and provides a Formableable form object like req.form. Your code value could be:

 ... app.use(express.bodyParser({defer: true})); ... // your upload handling request app.post('/upload', function(req, res)) { var incomingForm = req.form // it is Formidable form object incomingForm.on('error', function(err){ console.log(error); //handle the error }) incomingForm.on('fileBegin', function(name, file){ // do your things here when upload starts }) incomingForm.on('end', function(){ // do stuff after file upload }); // Main entry for parsing the files // needed to start Formidables activity incomingForm.parse(req, function(err, fields, files){ }) } 

For more detailed help on events see https://github.com/felixge/node-formidable

+15
Mar 27 '13 at 16:17
source share

I ran into similar problems in 3.1.1 and found a (not so pretty IMO) solution:

disable bodyParser for multipart / form-data:

 var bodyParser = express.bodyParser(); app.use(function(req,res,next){ if(req.get('content-type').indexOf('multipart/form-data') === 0)return next(); bodyParser(req,res,next); }); 

and to parse the content:

 app.all('/:token?/:collection',function(req,res,next){ if(req.get('content-type').indexOf('multipart/form-data') !== 0)return next(); if(req.method != 'POST' && req.method != 'PUT')return next(); //...use your custom code here }); 

for example, I use node-multipulty, where the user code should look like this:

  var form = new multiparty.Form(); form.on('file',function(name,file){ //...per file event handling }); form.parse(req, function(err, fields, files) { //...next(); }); 
+4
Apr 09 '13 at 1:54 on
source share

throw it up to app.configure

 delete express.bodyParser.parse['multipart/form-data']; 
+1
Jul 04 '12 at 5:11
source share



All Articles