如何使用node.js发布到请求

时间:2010-12-22 03:01:32

标签: javascript node.js http-post

我想将一些json发布到一个URL。我在stackoverflow上看到了关于这个的各种其他问题,但它们似乎都没有明确或有效。这是我得到了多远,我修改了api文档的例子:

var http = require('http');
var google = http.createClient(80, 'server');
var request = google.request('POST', '/get_stuff',
  {'host': 'sever',  'content-type': 'application/json'});
request.write(JSON.stringify(some_json),encoding='utf8'); //possibly need to escape as well? 
request.end();
request.on('response', function (response) {
  console.log('STATUS: ' + response.statusCode);
  console.log('HEADERS: ' + JSON.stringify(response.headers));
  response.setEncoding('utf8');
  response.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

当我将其发布到服务器时,我收到一个错误,告诉我它不是json格式或者它不是utf8,它们应该是。我试图拉取请求网址,但它是null。我刚开始使用nodejs所以请你好。

8 个答案:

答案 0 :(得分:39)

问题是您将Content-Type设置在错误的位置。它是请求标头的一部分,它们在options对象中有自己的密钥,这是request()方法的第一个参数。这是使用ClientRequest()实现一次性事务的实现(如果需要与同一服务器建立多个连接,可以保留createClient()):

var http = require('http')

var body = JSON.stringify({
    foo: "bar"
})

var request = new http.ClientRequest({
    hostname: "SERVER_NAME",
    port: 80,
    path: "/get_stuff",
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "Content-Length": Buffer.byteLength(body)
    }
})

request.end(body)

问题中的其余代码是正确的(request.on()及以下)。

答案 1 :(得分:14)

Jammus说得对。如果未设置Content-Length标头,则主体将在开始时包含某种长度,在结尾处包含0。

所以当我从Node发送时:

{"email":"joe@bloggs.com","passwd":"123456"}

我的rails服务器正在接收:

"2b {"email":"joe@bloggs.com","passwd":"123456"} 0  "

Rails不理解2b,所以它不会解释结果。

因此,为了通过JSON传递params,将Content-Type设置为application / json,并始终给出Content-Length。

答案 2 :(得分:9)

使用NodeJS将JSON作为POST发送到外部API ...(和" http"模块)

var http = require('http');

var post_req  = null,
    post_data = '{"login":"toto","password":"okay","duration":"9999"}';

var post_options = {
    hostname: '192.168.1.1',
    port    : '8080',
    path    : '/web/authenticate',
    method  : 'POST',
    headers : {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'Content-Length': post_data.length
    }
};

post_req = http.request(post_options, function (res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log('Response: ', chunk);
    });
});

post_req.on('error', function(e) {
    console.log('problem with request: ' + e.message);
});

post_req.write(post_data);
post_req.end();

答案 3 :(得分:6)

有一个非常好的库支持在Nodejs中发送POST请求:

链接:https://github.com/mikeal/request

示例代码:

var request = require('request');

//test data
var USER_DATA = {
    "email": "email@mail.com",
    "password": "a075d17f3d453073853f813838c15b8023b8c487038436354fe599c3942e1f95"
}

var options = {
    method: 'POST',
    url: 'URL:PORT/PATH',
    headers: {
        'Content-Type': 'application/json'
    },
    json: USER_DATA

};


function callback(error, response, body) {
    if (!error) {
        var info = JSON.parse(JSON.stringify(body));
        console.log(info);
    }
    else {
        console.log('Error happened: '+ error);
    }
}

//send request
request(options, callback);

答案 4 :(得分:4)

尝试包含内容长度。

var body = JSON.stringify(some_json);
var request = google.request('POST', '/get_stuff', { 
    host: 'server',
    'Content-Length': Buffer.byteLength(body),
    'Content-Type': 'application/json' 
    });
request.write(body);
request.end();

答案 5 :(得分:3)

这可能无法解决您的问题,但是javascript不支持命名参数,所以您要说:

request.write(JSON.stringify(some_json),encoding='utf8');

你应该说:

request.write(JSON.stringify(some_json),'utf8');

encoding =分配给一个全局变量,因此它是有效的语法,但可能没有按你的意愿行事。

答案 6 :(得分:2)

在提出此问题时可能不存在,您现在可以使用更高级别的库来处理http请求,例如https://github.com/mikeal/request。 Node的内置http模块对于初学者来说太低了。

Mikeal的请求模块内置支持直接处理JSON(请参阅文档,尤其是https://github.com/mikeal/request#requestoptions-callback)。

答案 7 :(得分:1)

var request = google.request(
  'POST',
  '/get_stuff',
  {
    'host': 'sever',
    **'headers'**:
    {
      'content-type': 'application/json'
    }
  }
);