无法使用NodeJS / ExpressJS和Postman获取POST数据 [英] Can't get POST data using NodeJS/ExpressJS and Postman
问题描述
这是我服务器的代码:
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上监听!’);
});
从邮递员,我向
添加请求的编码。这是一个示例
..
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({Extended:true}));
..
然后选择 x-www-form-urlencoded
或将Content-Type设置为 application / json
并选择 raw
编辑以使用原始
原始
{
foo: bar
}
标题
内容-类型:application / json
EDIT#2 回答聊天中的问题:
- 为什么它不能使用表单数据?
您当然可以,只需查看此答案如何处理Express 4中的FormData
- 使用
x-www-form-urlencoded
和raw
$ b $有什么区别b
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数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!