Express.js POST req.body 空

Express.js POST req.body empty

所以我的 server.js 文件中有以下代码,我是 运行 node.js。我正在使用 express 处理 HTTP 请求。

app.post('/api/destinations', function (req, res) {
  var new_destination = req.body;
  console.log(req.body);
  console.log(req.headers);
  db.Destination.create(new_destination, function(err, destination){
    if (err){
      res.send("Error: "+err);
    }
    res.json(destination);
  });
});

我是 运行 终端中的以下人员:

curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations

在 运行 之后 server.js 打印出以下内容。

{}
{ host: 'localhost:3000',
  'user-agent': 'curl/7.43.0',
  accept: '*/*',
  'content-type': 'application/json',
  'content-length': '53' }

所以 req.body 是 {}。我阅读了其他 Stack Overflow 的帖子,内容涉及类似的问题,其中内容类型因正文解析器而不正确。但这不是问题,因为内容类型是 application/json.

关于如何获取请求的实际正文的任何​​想法?

提前致谢。

您还需要bodyParser.json:

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

有时,如果您忘记将名称属性放入表单输入字段,req.body 会显示 {}。下面是一个例子:

<input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required>

然后 req.body 显示 { myemail: 'mathewjohnxxxx@gmail.com' }

我 post 这个答案是因为,我遇到了类似的问题,这对我有用。

确保如果您在 javascript 中制作表单和输入,请确保您将输入附加到表单。那是我的问题。

yourForm.appendChild(yourInput);

对我来说,后端配置正确问题是有效的 JSON 格式,包括变量上的双引号。

这没用

      const res = await axios.post(serverPath + "/user/login", {
         email: email,
         password: password,
      });

这个 DID 有效(用双引号括起电子邮件和密码

      const res = await axios.post(serverPath + "/user/login", {
         "email": email,
         "password": password,
      });