通过http.request发出请求时,req.body为空 [英] req.body is empty when making a post request via http.request

查看:3122
本文介绍了通过http.request发出请求时,req.body为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用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是空的
我正在做同样的调用,这里是一个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");

请求正文为空 - > {}

request body is empty -> {}

为什么?我尝试设置内容长度,但不做任何事情。

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'
};

应该做的伎俩。

strong>编辑:如果您发现自己在节点中执行了大量客户端HTTP请求,我衷心地推荐 Mikeal Rogers'请求模块,这使得这些东西变得轻而易举。

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发出请求时,req.body为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆