I have read all the documentation I can find, but I can not find a simple explanation of what these two middleware do.
What does the body
in body-parser
refer to? Why does the body need to be parsed?
Similarly for cookies. Am I correct that cookie-parser
"parses" or beaks down the cookies that accompany a web user?
Lastly, I have read that body-parser
is both unsafe and deprecated in Express4. Should I not use it?
In Express 4, body-parser and cookie-parser were moved to separate modules. The body and cookie parsers that were deprecated were the ones that shipped with Express 3.
The body parser parses request bodies. Those could contain like json or url encoded form data. The form data will then appear in req.body
.
The cookie parser parses cookies and puts the cookie information on req
object in the middleware. It will also decrypt signed cookies provided you know the secret.
As you may know, Node.js provides by default a very low level HTTP module. That's why you need "frameworks" like Express and such - they let you easily handle common features of web servers in other platforms (like Java and PHP, for example).
body-parser
body-parser
will take the body of your request and parse it to whatever you want your server to receive in POST
/PUT
requests (JSON, URL encoded, text, raw).
The only problem with body-parser (the far I know) is that you can't handle multipart bodies (which are commonly uploads).
Since Express version 4.16+ body-parser
is included as a built-in middleware function in Express, there is no need to install it.
cookie-parser
cookie-parser
will parse the Cookie
header and handle cookie separation and encoding, maybe even decrypt it!
Since Express 4.x cookie-parser
is a standalone middleware, and to use it you must install it first.
This all comes down to the fact that you don't need to use these features, and that's why Node is great.
You can simply ignore them and have your server less busy :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With