nodegrass将Nodejs原生HTTP请求的API进行了封装
nodejs文档对于http.get(options, [callback])的实例:
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
其中get方法的第二个参数是一个回调函数,我们异步的获取响应信息,然后,在该回调函数中,res对象又监听statusCode,on方法中第二个参数又是一个回调
来看一个nodegrass的get请求的例子:
var ng = require('nodegrass'),
http=require('http'),
url=require('url');
http.createServer(function(req,res){
var pathname = url.parse(req.url).pathname;
if(pathname === '/'){
ng.get('http://www.baidu.com/',function(data){
res.writeHeader(200,{'Content-Type':'text/html;charset=utf-8'});
res.write(data+"\n");
res.end();
},'utf8');
}
}).listen(8088);
console.log('server listening 8088...');
nodegrass会根据url自动识别是http还是https,当然你的url必须得有,不能只写www.baidu.com/而需要http://www.baidu.com/。
访问localhost端口8088即可得到百度页面
代理服务器?
nodegrass git传送门