fedesc
fedesc

Reputation: 2610

What is the difference between node's bodyParser and express's urlencoded middleware?

After reading about both i still can't wrap my head about it, could be language differences bu please help clarify.

express.urlencoded()

Returns middleware that only parses urlencoded bodies and only looks at requests where the Content-Type header matches the type option. This parser accepts only UTF-8 encoding of the body and supports automatic inflation of gzip and deflate encodings.

And

and body-parser middleware

Parse incoming request bodies in a middleware before your handlers, available under the req.body property.

i understand that express.urlencoded is based on Nodejs body-parser. and both pages,

https://expressjs.com/en/api.html#express.urlencoded

and

https://expressjs.com/en/resources/middleware/body-parser.html

even say the same warning note:

As req.body’s shape is based on user-controlled input, all properties and values in this object are untrusted and should be validated before trusting. For example, req.body.foo.toString() may fail in multiple ways, for example foo may not be there or may not be a string, and toString may not be a function and instead a string or other user-input.

but eventually both give me a req.body with params sent in requests body object. so why should i use body-parser (which i have to install separatly) instead of always using express.urlencoded()

I know this isn't a code problem but i thank in advance for anyone who can list up to the main differences.

Upvotes: 14

Views: 9080

Answers (1)

1565986223
1565986223

Reputation: 6718

so why should i use body-parser (which i have to install separatly) instead of always using express.urlencoded()

For the simple reason that it was not available in older version of express

This middleware is available in Express v4.16.0 onwards.

If you're using the latest version, there's almost no reason to.

body-parser provides a few additional utilities like bodyParser.raw([options]) or bodyParser.text([options]) which almost nobody uses (never seen use one myself).

Upvotes: 21

Related Questions