由于您要返回resp
,因此您似乎忘记了请求是异步的。而是试试这个:
var rest = require('restler');
var getResp = function(url){
rest.get(url).on('complete', function(response){
console.log(response);
});
};
getResp('http://google.com/');
// output:
// <!doctype html><html itemscope="itemscope" ....
由于它的异步特性,最好将值传递给接收回调。举个小例子:
var rest = require('restler');
// process an array of URLs
['http://google.com/',
'http://facebook.com/'].forEach(function(item) {
getResp(item);
});
function getResp(url){
rest.get(url).on('complete', function(response){
processResponse(response);
});
};
// data will be a Buffer
function processResponse(data) {
// converting Buffers to strings is expensive, so I prefer
// to do it explicitely when required
var str = data.toString();
}
一旦数据进来,你就可以像任何其他变量一样传递它。