node.js - 无法使用Node JS/Express JS和Postman获取POST数据

标签 node.js express postman body-parser

这是我的服务器的代码:

var express = require('express');
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.json());

app.post("/", function(req, res) {
    res.send(req.body);
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});

从Postman,我向http://localhost:3000/发起POST请求,并且在Body/form-data中,我有一个键“foo”和值“bar”。

但是我一直在响应中得到一个空对象。 req.body属性始终为空。

我错过了什么? enter image description here

最佳答案

添加请求的编码。这是一个例子

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

然后在Postman中选择x-www-form-urlencoded或将Content-Type设置为application/json并选择raw
编辑以使用原始格式

生的
{
  "foo": "bar"
}

header
Content-Type: application/json

编辑#2 聊天中的回答问题:
  • 为什么它不能与表单数据一起使用?

  • 您肯定可以,只需查看此答案How to handle FormData from express 4
  • 使用x-www-form-urlencodedraw
  • 有什么区别

    differences in application/json and application/x-www-form-urlencoded

    关于node.js - 无法使用Node JS/Express JS和Postman获取POST数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41955103/

    相关文章:

    java - Postman 请求返回 406 错误,仍然有效

    node.js - mongodb mongoose nodejsexpress4 为什么会自动在对象数组字段中插入_id?

    javascript - Node.js:路由优先级和排序 (sails.js)

    由于一个页面上的 MIME 类型,CSS 无法加载,但在另一个页面上工作正常

    api - 使用 POSTMAN 提交表单

    node.js - Sequelize : Issue in bulkCreate while inserting an array

    javascript - 请求- promise : downloading/checking a file's MIME type?

    json - 通过 socket.io 发送匿名函数?

    javascript - 使用 meteor job collection 开始工作

    javascript - 为什么 axios 在解析 twitter 搜索 api 响应后以某种方式修改推文的 id?