通过 http.request 发出 post 请求时 req.body 为空 [英] req.body is empty when making a post request via http.request
问题描述
我有一个使用 bodyparser() 的 nodejs 应用程序,这条路线:
I have a nodejs app using bodyparser(), and this route :
app.post('/users', function(req, res){
res.json(req.body)
})
当我卷曲时
curl -X POST 127.0.0.1:3000/users -d 'name=batman'
服务器发回这个json:
server sends back this json :
{ name: 'batman' }
我的问题是尝试使用 http.request 发出相同请求时,req.body 为空我在做同样的调用,这是我用 node 运行的 test.js 文件:
my problem is when trying to make the same request with http.request, req.body is empty i'm doing the same call though, here is a test.js file that i run with node :
var http = require('http');
var options = {
host: '127.0.0.1',
port: 3000,
path: '/api/users',
method: 'POST'
};
var request = http.request(options, function (response) {
var str = '';
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
});
});
request.end("name=batman");
请求正文为空 -> {}
为什么?我试过设置 content-length 但没有做任何事情.
why ? i've tried setting content-length but does not do anything.
推荐答案
你需要传递一个 Content-Type
来告诉 bodyParser()
使用哪个解析器.对于常规表单数据,您应该使用 Content-Type: application/x-www-form-urlencoded
,因此:
You need to pass a Content-Type
to tell bodyParser()
which parser to use. For regular form data, you should use Content-Type: application/x-www-form-urlencoded
, so:
var options = {
host: '127.0.0.1',
port: 3000,
path: '/api/users',
method: 'POST',
'Content-Type': 'application/x-www-form-urlencoded'
};
应该可以.
如果你发现自己在 node 中做了很多客户端 HTTP 请求,我衷心推荐 Mikeal Rogers'request
模块,让这些事情变得轻而易举.
If you find yourself doing a lot of client HTTP requests in node, I heartily recommend Mikeal Rogers' request
module, which makes these things a breeze.
这篇关于通过 http.request 发出 post 请求时 req.body 为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!