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});
});
2
  • possible duplicate of How to return the response from an asynchronous call? Commented May 4, 2015 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 Commented May 4, 2015 at 14:17

1 Answer 1

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();
});
Sign up to request clarification or add additional context in comments.

2 Comments

Sometimes it works but sometimes I get unexpected end of input
well now you have a completely different problem not appropriate to this question... try and resolve it and if you cannot post a new SO question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.