aliez-apireq
Version:
aliez request api webrequest httprequest
81 lines (76 loc) • 1.99 kB
JavaScript
;
var http = require('http'), url = require('url');
var httpRequest = function(options, cb){
/* options:
*
* {
* url: {string}, // 请求地址
* method: {string}, // 请求方法
* headers: {object}, // 可选请求头
* data: {object} // 可选post数据
* }
*/
if('object' == typeof options){
if('string' != typeof options.url){
cb.call(this, new Error('no request url in option object'));
return;
}
var reqobj = url.parse(options.url);
delete reqobj.slashes;
delete reqobj.hash;
delete reqobj.search;
delete reqobj.query;
delete reqobj.pathname;
delete reqobj.href;
if(options.method){
reqobj.method = options.method;
}
if(options.headers){
reqobj.headers = options.headers;
if(options.data && options.method == 'POST'){
reqobj.headers['content-type'] = 'application/x-www-form-urlencoded';
}
}
var req = http.request(reqobj, function(res){
var buf = new Buffer('');
res.on('data', function(chunk){
buf = Buffer.concat([buf, chunk]);
}).on('end', function(){
try{
var json = JSON.parse(buf.toString());
if('function' == typeof cb){
cb.call(this, null, json);
}
}catch(e){
if('function' == typeof cb){
cb.call(this, null, buf.toString());
}
}
});
});
req.on('error', function(err){
if('function' == typeof cb){
cb.call(this, err);
}
}).on('timeout', function(){
if('function' == typeof cb){
cb.call(this, new Error('timeout'));
}
});
if(options.timeout){
req.setTimeout(options.timeout);
}
if(options.data && options.method == 'POST'){
req.end(JSON.stringify(options.data));
}else{
req.end();
}
}else{
if('function' == typeof cb) cb.call(this, new Error('No option object'));
}
}
var request = function(req, res, done){
req.apireq = httpRequest;
done();
}
module.exports = request;