Getting HTTP Response using restler in Node.js
httpresponse, javascript, node.js, restler
Solution
Being that you're returning `resp` it looks like you've forgotten that the request is asynchronous. Instead try out this:
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" ....
Because of its asynchronous nature it's preferred that you pass the value to a receiving callback. Take this small example:
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();
}
Once the data comes in you'll be able to pass it around like any other variable.
Problem
I don't understand why this code doesn't work for me ``` var rest = require('restler'); var getResp = function(url){ var resp =""; rest.get(url).on('complete',function(response){ resp = response.toString(); }); return resp; }; ``` I am not getting the response for `getResp('google.com')` Am I missing something with restler?