📜  body-parser 已弃用 (1)

📅  最后修改于: 2023-12-03 15:13:40.492000             🧑  作者: Mango

Deprecation of body-parser

The body-parser module has been deprecated, and is no longer recommended for use with Express.js.

What was body-parser used for?

body-parser was a popular middleware module used to parse and extract data from the request body of HTTP POST and PUT requests. It had support for different types of data formats like JSON, URL-encoded, text and more.

Why is it being deprecated?

With the release of Express.js 4.16+, body-parser has been built-in and can be accessed directly through req.body. This provides a better and more streamlined middleware for handling request bodies, eliminating the need for an external module.

Moreover, body-parser had security issues due to which it was not reliable for the safe parsing of HTTP requests.

What to use instead?

With the deprecation of body-parser, it is recommended to use express.urlencoded and express.json. These built-in middleware functions provide the same functionality as body-parser.

Here's an example:

const express = require('express');
const app = express();

// Middleware for handling request body
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
Conclusion

In conclusion, body-parser has been deprecated and it is recommended to use the built-in express.urlencoded and express.json middleware for parsing the request body in Express.js. This provides a secure and reliable way of handling HTTP requests.