node.js +发布请求

时间:2014-10-14 18:56:34

标签: node.js http-post

我正在尝试使用node.js调用另一个应用程序(在localhost:3000中运行)的post data方法。但它的返回错误..

以下是代码:

var options = {
  host: 'localhost',
  path: '/v1/key/11111111',
  //since we are listening on a custom port, we need to specify it by hand
  port: '3000',
  //This is what changes the request to a POST request
  method: 'POST',  
  headers: {'Content-Type': 'application/json'}
};

callback = function(response) {
  var str = ''
  response.on('data', function (chunk) {
    str += chunk;
  });

  response.on('end', function () {
    console.log(str);
  });
}

var req = http.request(options, callback);
//This is the data we are posting, it needs to be a string or a buffer
req.write("hello world!");
req.end();

但我收到错误:

{"meta":{"version":1,"status_code":400},"results":{"error":{"type":"Error","message":"invalid json"}}}

当我尝试使用CURL命令时,我得到了所需的结果:

curl -X POST  localhost:3000/v1/key/12345678 --header "Content-Type:application/json"

我的问题是如何构建POST request for the above requirement

1 个答案:

答案 0 :(得分:3)

您指定' application / json'在请求选项中。但是你提供字符串" Hello world!",这不是json,而且是错误信息告诉你的。

尝试更改标题或内容。