简体   繁体   中英

Express: Prevent bodyParser from parsing request

I am using Nodejs + Express version 4.14.0 like this:

var app = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
    extended: true
}));

This is needed and works as expected. However, for some requests I would like to force the application to not automatically parse the request to json but leave it as plain text, ie something like:

app.post('/myRequest', function (req.asPlainText(), res) {
    // req is not parsed to json now
});

Does anyone know how I can achieve that?

You can pass a string as the first argument to app.use() and it will only apply the middleware to paths that match. The documentation can be found at http://expressjs.com/en/4x/api.html#app.use .

An example:

app.use('/', bodyParser.json())

You could also declare any routes that do not need body-parser prior to adding it as a global middleware, but it is generally a good idea to only use body-parser where you actually need the body.

If you don't want to use app.use() for each route, you can also pass the middleware in the route declaration like:

app.post('/', bodyParser.json(), function(req, res) {
  // handle route here
})

To not use it for certain routes, just don't include it in the route.

create a variable with form.serialize and include result as parameter. var req = document.forms[0].serialize(); app.post('/myRequest', req, res) { // req is not parsed to json now });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM