说在前头
最近玩node.js,涉及到http的操作,搜索了下资料发现一个模块nodegrass挺不错,但看了下源码感觉太臃肿。
于是了解了下http的一些方法,然后做了个httpor模块,如果有兴趣直接输入下面命令安装即可:
$ npm install httpor
基础知识
先来看下如何使用http模块的request方法进行get请求发包:
var opt = {
method: 'GET',
headers: {
'User-Agent': 'httpor/1.0'
},
host: 'ursb.org',
port: 80,
path: '/'
}
http.request(opt, function(res){
var _html = '';
res.on('data', function(c){
_html += c;
}).on('end', function(){
console.log('请求完成');
console.log('状态码:' + res.statusCode);
console.log('头信息:' + res.headers);
console.log('数据:' + _html);
})
}).on('error', function(e){
console.log('请求错误');
console.log(e);
}).end();
很简单的代码,随手敲的,POST请求也类似,无非就是先定义一个请求信息对象,包含host,port等信息,不过注意的是POST请求设置中的method为POST,以及需要定义一个Content-Typ为application/x-www-form-urlencoded的headers头信息,这样才能让目标接收到我们的数据,
最后使用write方法把数据包写入操作对象中:
var opt = {
method: 'POST',
host: 'ursb.org',
port: 80,
path: '/api/posts.json',
data: {
id: 111,
name: 'test post data'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
var req = http.request(opt, function(res){
// …你懂的
});
req.write(querystring.stringify(opt.data));
req.end();
可以看出,只需要write一个格式化过后的数据就OK了。 那么,如何请求
https页面呢?很简单,把http模块换为https即可:
var https = require("https");
其他细节
使用request已经能满足大部分的操作了,但是呢,有个问题,就是网页的编码,并不是每个页面的编码设置都一样,所以我们就需要第三方模块iconv-lite来处理编码了,当然,有能力自己写也是可以的~
优化处理
我们怎么封装才能使用更方便呢?参考jQuery.ajax?不错的想法,可以先写下方便操作的代码:
myhttp.get("http://ursb.org/", function(res){
console.log(res);
});
myhttp.post("http://ursb.org/api/posts.json", {
data: 'testdata'
}, function(res){
console.log(res);
});
myhttp.ajax({
url: 'http://ursb.org',
method: 'POST',
success: function(res){
console.log(res);
}
});
…
这样封装就很方便了吧!完全模拟的jQuery,怎么写这一个封装函数?具体你都懂的。。