Node.js 0.12: 正确发送HTTP POST请求

本文针对版本:Node.js 0.12.4

之前写过一篇Node.js发送和接收HTTP的GET请求的文章,今天再写一篇,讲发送POST的请求,当然,也是不借助任何外力,使用Node.js原生Module。

发送POST请求,相比GET会有些蛋疼,因为Node.js(目前0.12.4)现在还没有直接发送POST请求的封装。发送GET的话,使用http.get可以直接传一个字符串作为URL,而http.get方法就是封装原始的http.request方法。发送POST的话,只能使用原始的http.request方法,同时因为要设置HTTP请求头的参数,所以必须传入一个对象作为http.request的第一个options参数(而不是URL字符串)。另外,options参数中的hostname需要的是不带协议的URL根路径,子路径需要在path属性单独设置。如果hostname包含了完整的URL,通常会遇到错误:Error: getaddrinfo ENOTFOUND http://www.xxx.com/xxx。

这里可以使用url Module进行协助,使用url.parse返回值的hostnamepath属性就可以,测试代码:

var url = require('url');
console.log(url.parse('http://www.mgenware.com/a/b/c'));

输出:

{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: 'www.mgenware.com',
  port: null,
  hostname: 'www.mgenware.com',
  hash: null,
  search: null,
  query: null,
  pathname: '/a/b/c',
  path: '/a/b/c',
  href: 'http://www.mgenware.com/a/b/c' }

OK,hostnamepath参数解决后,然后就是常见POST请求HTTP Header属性的设置,设置methodPOST,另外如果是模拟HTML <form>的POST请求的话,Content-Type应当是application/x-www-form-urlencoded,最后别忘了Content-Length,而且,如果Content是字符串的话最好用Buffer.byteLength('字符串', 'utf8')来获取字节长度(而不是直接'字符串'.length,虽然使用URL编码的ASCII字符串每个字符是1字节)。

然后就是回调的处理,这个在上篇文章中又讲过,Callback中的第一个res参数是执行Readable Stream接口的,通过resdata事件来把chunk存在数组里,最后在end事件里使用Buffer.concat把数据转换成完整的Buffer,需要的话,通过Buffer.toStringBuffer转换成回应的字符串。

完整代码(我们使用httpbin.org做POST测试):

var querystring = require('querystring');
var url = require('url');
var http = require('http');
var https = require('https');
var util = require('util');

//POST URL
var urlstr = 'http://httpbin.org/post';
//POST 内容
var bodyQueryStr = {
name: 'mgen',
id: 2345,
str: 'hahahahahhaa'
};

var contentStr = querystring.stringify(bodyQueryStr);
var contentLen = Buffer.byteLength(contentStr, 'utf8');
console.log(util.format('post data: %s, with length: %d', contentStr, contentLen));
var httpModule = urlstr.indexOf('https') === 0 ? https : http;
var urlData = url.parse(urlstr);

//HTTP请求选项
var opt = {
hostname: urlData.hostname,
path: urlData.path,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': contentLen
}
};

//处理事件回调
var req = httpModule.request(opt, function(httpRes) {
var buffers = [];
httpRes.on('data', function(chunk) {
buffers.push(chunk);
});

httpRes.on('end', function(chunk) {
var wholeData = Buffer.concat(buffers);
var dataStr = wholeData.toString('utf8');
console.log('content ' + wholeData);
});
}).on('error', function(err) {
console.log('error ' + err);
});;

//写入数据,完成发送
req.write(contentStr);
req.end();

运行完毕后,会以字符串输出HTTP回应内容。

posted @ 2015-09-02 11:34  meetrice  阅读(2084)  评论(0编辑  收藏  举报