HTTP请求node.js使用mikeal的'request'

时间:2012-04-05 15:50:13

标签: node.js httprequest

我正在尝试使用https://github.com/mikeal/request。我的代码出了什么问题?错误消息在代码下。在我的程序中,我正在使用我的真实App和Rest ID

var request = require('request');
request.post( {
url: 'https://api.parse.com/1/classes/GameScore',
headers: {
    "X-Parse-Application-Id": "11111",
    "X-Parse-REST-API-Key": "222222",
    "Content-Type": "application/json" 
         },
body: {
    "score": 1337, "playerName": "Sean Plott", "cheatMode": false
    }
 }, 
function (error, response, body) {
  if(response.statusCode == 201){
    console.log('Status Update');
  } else {
    console.log('error: '+ response.statusCode);
    console.log(body);
  }
}
);

错误讯息:

node.js:134
    throw e; // process.nextTick error, or 'error' event on first tick
    ^
Error: Argument error, options.body.
at Request.init (/mnt/ws/users/$mn/mnort9/165767/node_modules/request/main.js:264:13)
at new Request (/mnt/ws/users/$mn/mnort9/165767/node_modules/request/main.js:102:8)
at request (/mnt/ws/users/$mn/mnort9/165767/node_modules/request/main.js:800:11)
at Function.post (/mnt/ws/users/$mn/mnort9/165767/node_modules/request/main.js:844:10)
at Object. (/mnt/ws/users/$mn/mnort9/165767/index.js:2:9)
at Module._compile (module.js:411:26)
at Object..js (module.js:417:10)
at Module.load (module.js:343:31)
at Function._load (module.js:302:12)
at Array.<anonymous> (module.js:430:10)

2 个答案:

答案 0 :(得分:39)

body应该是字符串,数组或缓冲区。不是一个对象。

如果你想发送json然后发送json

request({
    ...,
   json: { ... }
})

答案 1 :(得分:1)

我认为最好的

r = npm.request(options, function (error, response, body) {

if (error) {
var msg = error.code || 'Error code undefined!';
return;
};

//and after

if((response.statusCode == 200) || (response.statusCode == 201)){
}

}