首页 > 解决方案 > 如何让我的示例 bodyparser 工作?

问题描述

我正在尝试使用邮递员发送一个 post 方法来接收一些示例参数。但是我的示例代码无法识别req.body,所以它总是空的。

这是我的示例代码:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();


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

app.post('/', function(req, res){
  console.log(req.body)
})

app.listen(2001, function () {
  console.log('Listening on port 2001!');
});

如果我像这样使用邮递员: 点击这里!

我总是得到一个空的 console.log

标签: javascriptnode.jsbody-parser

解决方案


您将参数作为查询字符串发送,因此req.body您必须使用而不是使用:req.query

bodyParser将在您的情况下解析x-www-form-urlencoded,因为您正在使用:

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

推荐阅读