为什么我收到 'bodyParser' is deprecated 警告?

Why am I getting 'bodyParser' is deprecated warning?

我使用了这两个软件包的最新版本,但我仍然收到 'bodyParser' 是不推荐使用的警告。它不会影响我的代码,但为什么会这样?

const express =  require("express")
const bodyParser =  require("body-parser")

let app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.listen(port, () => {
    console.log(`Welcome to ${port}`);
});

这意味着 body-parser 希望您使用不同的方法(.json() 或 .urlencoded()):

https://github.com/expressjs/body-parser/commit/b7420f8dc5c8b17a277c9e50d72bbaf3086a3900

我的项目也出现同样的问题。 现在在最新的 express 中我们不需要导入 body-parse,我们可以像下面这样使用 express。

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

或 如果你限制尺寸

app.use(express.urlencoded({ limit: "50mb", extended: false, parameterLimit: 500000000 }));

我认为最好不要再使用 body-parser

从 Express 4.16+ 开始,正文解析功能已内置到 express 中

你可以做到

app.use(express.urlencoded({extended: true}));
app.use(express.json()) // To parse the incoming requests with JSON payloads

直接表达,无需安装 body-parser。

所以你可以使用 npm uninstall body-parser 卸载 body-parser,并使用上面的 express