【发布时间】:2022-02-03 05:02:36
【问题描述】:
我在我的发布请求中得到了一个未定义的 req.body,尝试了所有方法,从 body-parser 到 express.json,两者都在一起(肯定不好),但仍然无法让它工作。非常感谢任何帮助!
我已将我的 nodejs 服务器减少到最低限度:
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.post('/requests', (req, res) => {
console.log(req.body);
res.status(201).json('all ok');
})
app.listen(4000, () => {console.log('Server listening on port 4000')});
我的请求是(使用 VS Code 的 REST 客户端完成):
POST http://localhost:4000/requests
Content-Type: 'application/json'
{
"msg":"Some message",
"other":"Other msg"
}
【问题讨论】:
-
附加信息:我使用 nodejs 版本 12.22.9(需要它在旧的 32 位机器上运行)并表示 14.17.2。不知道会不会有影响……
-
这是您的示例的一个稍微修改的实例,按预期工作:runkit.com/6181458f0d176000085690c3/61fae0ca7f1c740008e41379 - 使用 express.bodyParser 或 body-parser 模块没有区别。我找不到您上面显示的任何问题(除了缺少导入 express 模块的事实,我假设您只是在整理示例时忘记包含它)