cascavel
cascavel

Reputation: 191

express.js: how to use value returned by http.request in app.get

I want to use app.get to deliver the data from an API on another domain. I can write the data to the console, but nothing is appearing on the page ('~/restresults').

This is the code I have so far:

app.get('/restresults', function (req, res) {

        var theresults;
        var http = require('http');
        var options =  {
            port: '80' ,
            hostname: 'restsite' ,
            path: '/v1/search?format=json&q=%22foobar%22' ,
            headers: { 'Authorization': 'Basic abc=='}
        } ;

        callback = function(res) {
            var content;
            res.on('data', function (chunk) {
                content += chunk;
            });

            res.on('end', function () {
                console.log(content);
                theresults = content ;
            });
        };
       http.request(options, callback).end();

      res.send(theresults) ; 

});

how can I bind the result of the http.request to a variable and return it when 'restresults/' is requested?

Upvotes: 0

Views: 2860

Answers (2)

Jite
Jite

Reputation: 5847

You are currently sending the response before the callback (from the http request) is done.
The http.request is async, the script will not wait til its done and then send the data back to client.

You will have to wait for the request to be done and then send the result back to the client (preferably in the callback function).

Example:

http.request(options, function(httpRes) {  
  // Notice that i renamed the 'res' param due to one with that name existing in the outer scope.

  /*do the res.on('data' stuff... and any other code you want...*/
  httpRes.on('end', function () {
    res.send(content);
  });
}).end();

Upvotes: 2

Jordonias
Jordonias

Reputation: 5848

Move res.send(theresults); to here:

callback = function(res2) {
  var content;
  res2.on('data', function (chunk) {
    content += chunk;
  });

  res2.on('end', function () {
    console.log(content);
    theresults = content ;
    res.send(theresults) ; // Here
  });
};

Note: You'll have to change res to something else as you want the express res, no the request res.

The callback is an asynchronous call. You're sending the response before you get a result from the request.

You'll also want to handle the case in which there is an error, otherwise the client's request may hang.

Upvotes: 2

Related Questions