问题描述
这是我服务器的代码:
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('监听 3000 端口的示例应用程序!');});
从 Postman,我向
添加请求的编码.这是一个例子
..app.use(bodyParser.json());app.use(bodyParser.urlencoded({extended: true }));..
然后在 Postman 中选择 x-www-form-urlencoded
或者将 Content-Type 设置为 application/json
并选择 raw
编辑以使用 raw
原始
{富":酒吧"}
标题
内容类型:application/json
EDIT #2回答聊天中的问题:
- 为什么它不能与表单数据一起使用?
你当然可以,看看这个答案How to handle FormData from express4
- 使用
x-www-form-urlencoded
和raw
有什么区别
application/json 和 application/x 的区别-www-form-urlencoded
This is the code of my server :
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!');
});
From Postman, I launch a POST request to http://localhost:3000/ and in Body/form-data I have a key "foo" and value "bar".
However I keep getting an empty object in the response. The req.body
property is always empty.
Did I miss something?
Add the encoding of the request. Here is an example
..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
..
Then select x-www-form-urlencoded
in Postman or set Content-Type to application/json
and select raw
Edit for use of raw
Raw
{
"foo": "bar"
}
Headers
Content-Type: application/json
EDIT #2 Answering questions from chat:
- why it can't work with form-data?
You sure can, just look at this answer How to handle FormData from express 4
- What is the difference between using
x-www-form-urlencoded
andraw
differences in application/json and application/x-www-form-urlencoded
这篇关于无法使用 NodeJS/ExpressJS 和 Postman 获取 POST 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!