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

我试图发布一些JSON到一个URL。 我看到了关于这个在stackoverflow其他各种问题,但他们都没有看起来很清楚或工作。 这是我得到了多less,我修改了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,他们应该是。 我试图拉请求的url,但它是空的。 我只是从nodejs开始,所以请好。

问题是你在错误的地方设置Content-Type。 它是请求标头的一部分,在请求对象中有自己的关键字,这是request()方法的第一个参数。 这是一个使用ClientRequest()进行一次性事务的实现(如果需要与同一个服务器build立多个连接,可以保留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()及以下)。

Jammus得到了这个权利。 如果Content-Length头没有设置,那么主体将在开始处包含某种长度,在结尾处包含一个0。

所以当我从Node发送时:

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

我的导轨服务器正在接收:

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

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

所以,要通过JSON传递参数,将Content-Type设置为application / json,并且始终给出Content-Length。

要将JSON作为POST发送到具有NodeJS的外部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(); 

这可能不能解决你的问题,但JavaScript不支持命名参数,所以你说:

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

你应该说:

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

encoding =正在分配给一个全局variables,所以它是有效的语法,但可能不是你想要的。

有一个非常好的库支持在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); 

尝试包括内容的长度。

 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(); 

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

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

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