Express JS— body-parser and why may not need it | by Michael Majdanski | Medium
Nội Dung Chính
Express JS— body-parser and why may not need it
ExpressJS, not to be confused with Espresso (which people still pronounce incorrectly)
Node/Express
Many of us that have been using the Node/Express Framework have been used to installing another piece of middleware in order for us to be able to read the “body” of an incoming JSON object. This piece of middleware was called body-parser and used to not be part of the Express framework. The good news is that as of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.
Purpose
The purpose of this very short article is to get you to stop running this command if you are using Express 4.16+(unless you absolutely have a need for it [see the Conclusion for more info]):
npm install --save body-parser
You may have added a line to your code that looks like the following:
app.use(bodyparser.json()); //utilizes the body-parser package
If you are using Express 4.16+ you can now replace that line with:
app.use(express.json()); //Used to parse JSON bodies
This should not introduce any breaking changes into your applications since the code in express.json() is based on bodyparser.json().
If you also have the following code in your environment:
app.use(bodyParser.urlencoded({extended: true}));
You can replace that with:
app.use(express.urlencoded()); //Parse URL-encoded bodies
Conclusion
You might not need to install the additional body-parser package to your application if you are using Express 4.16+. There are many tutorials that include the installation of body-parser because they are dated prior to the release of Express 4.16.
A final note of caution: There are still some very specific cases where body-parser might still be necessary but for the most part Express’ implementation of body-parser is all you will need for the majority of use cases (see the docs at github.com/expressjs/body-parser for more details).