最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting HTTP Response using restler in Node.js - Stack Overflow

programmeradmin1浏览0评论

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('plete',function(response){
          resp = response.toString();
        });
        return resp;
    };

I am not getting the response for getResp('google')

Am I missing something with restler?

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('plete',function(response){
          resp = response.toString();
        });
        return resp;
    };

I am not getting the response for getResp('google.')

Am I missing something with restler?

Share Improve this question asked Jul 10, 2013 at 6:57 Nick GinantoNick Ginanto 32.2k49 gold badges141 silver badges250 bronze badges 2
  • did you try getResp('http://google.')? – Scott Bartell Commented Jul 10, 2013 at 7:13
  • something thing.. I get '' – Nick Ginanto Commented Jul 10, 2013 at 7:14
Add a ment  | 

2 Answers 2

Reset to default 4

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('plete', function(response){
    console.log(response);
  });
};

getResp('http://google./');

// 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./',
'http://facebook./'].forEach(function(item) {
  getResp(item);
});

function getResp(url){
  rest.get(url).on('plete', 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 es in you'll be able to pass it around like any other variable.

return resp; is running before the on('plete' callback gets called because it is asynchronous. This is resulting is the resp variable never getting assigned a value.

Try this:

var rest = require('restler');

var getResp = function(url){
  var result = rest.get(url).on('plete', function(response){
   response;
  });
  return result;
};

getResp('http://google./');

You could also use a callback like in this SO answer.

发布评论

评论列表(0)

  1. 暂无评论