crispychicken
crispychicken

Reputation: 2662

variable is not defined inside http request in node and express

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});
});

Upvotes: 1

Views: 277

Answers (1)

DrCord
DrCord

Reputation: 3955

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();
});

Upvotes: 2

Related Questions