Skip to content Skip to sidebar Skip to footer

Migrating Away From Bodyparser() In Express App With Busboy?

Being a newbie in Nodejs, I jumped right into writing a simple app without really reading up on good security practices. I just found out that using bodyParser() for all routes is

Solution 1:

[How] I can specify which route should handle multipart data and which should not?

All of Express' routing methods allow for providing middleware specific to the route. This includes Router methods.

app.METHOD(path, callback [, callback ...])

Depending on the body expected for an individual route, you can use different modules to handle each of them (rather than applying them to the entire application with app.use()).

var express = require('express');
var app = express();
var http = require('http').Server(app);

var bodyParser = require('body-parser');
var busboy = require('connect-busboy');

app.post("/form_data_no_fileupload",
    bodyParser.urlencoded(),
    function(req, res, next) {
        // check that the request's body was as expectedif (!req.body) returnnext('route'); // or next(new Error('...'));// ...
    });

app.post("/form_data_AND_fileupload",
    busboy({
        limits: {
            fileSize: 10 * 1024 * 1024
        }
    }),
    function(req, res, next) {
        // check that the request's body was as expectedif (!req.busboy) returnnext('route'); // or next(new Error('...'));// ...
    });

// ...

Furthermore, busboy docs says it does not handle GET.

So, I'm even more confused how I would parse params in a GET.

Busboy and BodyParser are designed for reading in and parsing the request's body, which GET and HEAD requests aren't expected to have.

For such requests, parameters can only be passed within the query-string within the URL, which Express parses itself. They're available via req.query.

app.get('/get_something', function () {
    console.log(req.originalUrl);
    // "/get_something?id=1console.log(req.query);
    // { id: "1" }
});

req.params represents any placeholders matched in the path by the route. These are available for any route, regardless of the method.

app.get('/thing/:id', function (req, res) {
    console.log(req.originalUrl);
    // "/thing/2"console.log(req.params);
    // { id: "2" }
});

Post a Comment for "Migrating Away From Bodyparser() In Express App With Busboy?"