首页 > 解决方案 > 在 Express JS Api 中使用 Put 方法时,是否需要使用正文解析器?

问题描述

在下面的代码片段中,我是否需要像在 Post 方法中那样使用 urlencodedParser。

app.put('/api/provider/:id', urlencodedParser, function (req, res) {

}

标签: node.jsexpressput

解决方案


body-parser将请求的主体解析为req.body,您的put中间件可能需要它。body-parser现在内置于 Express 中(从v4.16.0 开始- 下面假设您有更新版本)。

最简单的实现是在所有请求中使用express.jsonand express.urlencoded(used in ) , using ,这样您就不必在中间件中担心它。以下是为您设置的方法:body-parserapp.usenpx express-generator $APP_NAME

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

注意:如果您期望在您的 requests 中有嵌套对象,则需要设置extended为。true


推荐阅读