1

In my express action get('items') I'm calling an external JSON-API and would like to render the API response in my local response.

Currently I get an error that my items variable is not defined inside of the http request. It seems this is a scope issue but I didn't find a solution.

What is the best way to accomplish this?

var http = require('http');

router.get('/items', function (req, res, next) {
    var items;

    var RemoteRequest = http.request({
        method: 'GET',
        path: 'myurl'
    }, function (response) {
        response.on('data', function (data) {
            items = JSON.parse(data);
        });
    });

    RemoteRequest .end();
    res.render('new', {items: items} );
    // or res.json({items: items});
});
crispychicken
  • 2,592
  • 2
  • 33
  • 50
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Rodrigo Medeiros May 04 '15 at 14:17
  • res.render is getting called before the http request has a chance to get a response. You should put the res.render in the response.on(... function – Charlie Wynn May 04 '15 at 14:17

1 Answers1

2

It looks like you are not waiting for the return from your http request, you need to move the res.render('new', {items: items} ); into the callback:

var http = require('http');

router.get('/items', function (req, res, next) {
    var items;

    var RemoteRequest = http.request({
        method: 'GET',
        path: 'myurl'
    }, function (response) {
        response.on('data', function (data) {
            items = JSON.parse(data);
            res.render('new', {items: items} );
            // or res.json({items: items});
        });
    });

    RemoteRequest .end();
});
DrCord
  • 3,917
  • 3
  • 34
  • 47