Can I use multiparty for a single route in my express app?

624 Views Asked by At

I have an Express 3 app that uses bodyParser for most routes. (Most routes only accept multipart.) I have a single route that is going to be parsing files up to 1GB in size which bodyParser can't seem to handle. I would like to use multiparty for only this route so I don't have to rewrite the whole API. Is this possible?

1

There are 1 best solutions below

4
On BEST ANSWER

You can supply middleware to a single route by doing this:

var multipartyMiddleware = function (req,res,next){
  //put your code to parse multipart here and call "next" when done
}

app.post('/this/is/a/single/route', multipartyMiddleware, function(req,res){
  //do normal business logic in this route and send the response
})

If you need to bypass the multipart parsing in the old bodyParser in express 3 you can replace this:

app.use(express.bodyParser())

with this:

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

This works because the source of the bodyParser middleware reveals that it is just a combo of three middleware parsers: multipart, json, and urlencoded.

see the connect 2.X source here: https://github.com/senchalabs/connect/blob/2.x/lib/middleware/bodyParser.js#L54