Getting HTTP response using restler in Node.js

I do not understand why this code does not 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 do not get an answer for getResp('google.com')

Am I missing something with a wrestler?

+4
source share
2 answers

If you return resp , it looks like you forgot that the request is asynchronous. Try instead:

 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" .... 

Due to its asynchronous nature, it prefers to pass the value to the 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 arrives, you will be able to transfer it, like any other variable.

+4
source

return resp; is executed before calling callback on('complete' , because it is asynchronous. As a result, the resp variable arises, which is never assigned a value.

Try the following:

 var rest = require('restler'); var getResp = function(url){ var result = rest.get(url).on('complete', function(response){ response; }); return result; }; getResp('http://google.com/'); 

You can also use a callback, as in this SO answer .

+1
source

Source: https://habr.com/ru/post/1490644/


All Articles