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

Mr *_*SON 31 javascript http-post node.js

我试图将一些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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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

Ank*_*wal 40

问题是您将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)
Run Code Online (Sandbox Code Playgroud)

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

  • 请不要使用data.length,我碰到了这个问题,作者说不要使用data.length,而是使用Buffer.byteLength(data).参考问题:http://stackoverflow.com/questions/18692580/node-js-post-causes-error-socket-hang-up-code-econnreset和ref issue:https://github.com/visionmedia/express/问题/ 1749 (3认同)

Jon*_*nor 14

贾姆斯姆做对了.如果未设置Content-Length标头,则主体将在开始时包含某种长度,在结尾时包含0.

所以当我从Node发送时:

{"email":"joe@bloggs.com","passwd":"123456"}
Run Code Online (Sandbox Code Playgroud)

我的rails服务器正在接收:

"2b {"email":"joe@bloggs.com","passwd":"123456"} 0  "
Run Code Online (Sandbox Code Playgroud)

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

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

  • "总是给出内容长度." 非常感谢非常有帮助 (2认同)

mol*_*oco 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();
Run Code Online (Sandbox Code Playgroud)


Dio*_*ung 7

有一个非常好的库支持在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);
Run Code Online (Sandbox Code Playgroud)


jam*_*mus 5

尝试包括内容长度。

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();
Run Code Online (Sandbox Code Playgroud)


Ran*_*Etc 4

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

request.write(JSON.stringify(some_json),encoding='utf8');
Run Code Online (Sandbox Code Playgroud)

你应该说:

request.write(JSON.stringify(some_json),'utf8');
Run Code Online (Sandbox Code Playgroud)

编码 = 分配给全局变量,因此它是有效的语法,但可能没有达到您的预期。