Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do nodes Body Parser and cookie parser do? And should I use them?

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?

like image 928
Startec Avatar asked Oct 17 '14 03:10

Startec


2 Answers

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.

like image 52
Josh C. Avatar answered Nov 09 '22 00:11

Josh C.


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 :)

like image 13
gustavohenke Avatar answered Nov 08 '22 23:11

gustavohenke