Home > OS >  getting and passing object to node js render method
getting and passing object to node js render method

Time:09-23

I am playing around with the alpha vantage API and I am having trouble extracting the data in the else statement for viewing on the front end.

Here is my express route:

app.get('/', (req, res) => {
var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=apikey';
request.get({
    url: url,
    json: true,
    headers: { 'User-Agent': 'request' }
}, (err, resp, data) => {
    if (err) {
        console.log('Error:', err);
    } else if (resp.statusCode !== 200) {
        console.log('Status:', resp.statusCode);
    } else {
        // data is successfully parsed as a JSON object:
        // console.log(data);
    }
})
res.render("index");

})

I want to pass the data variable in the else statement to res.render("index" {//get data into here});

I have tried assigning the data variable to another variable outside of request.get({}) but it does not seem to work. Any suggestions? :)

CodePudding user response:

You can render it in the else statement.

app.get('/', (req, res) => {
    var url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=apikey';
    request.get({
        url: url,
        json: true,
        headers: { 'User-Agent': 'request' }
    }, (err, resp, data) => {
        if (err) {
            console.log('Error:', err);
        } else if (resp.statusCode !== 200) {
            console.log('Status:', resp.statusCode);
        } else {
            res.render("index", {data}) // Change to something else
        }
    })

}}

CodePudding user response:

request.get is an asynchronous function, it means that everything inside the callback function below won't be executed immediately, it will wait until the request.get finish calling the endpoint and return the data then callback function will be executed.

// the callback function of `request.get`
(err, resp, data) => {
        if (err) {
            console.log('Error:', err);
        } else if (resp.statusCode !== 200) {
            console.log('Status:', resp.statusCode);
        } else {
            // data is successfully parsed as a JSON object:
            // console.log(data);
        }
    })

In terms of execution flow, your res.render("index"); will be executed first before the callback function of request.get (it waits until the endpoint call finished), that's why you couldn't access data.

So, in order to res.render to access data, it should be put inside callback function so

(err, resp, data) => {
        // ...other code
        } else {
            res.render('index', { data });
        }
    })

good reference to read about asynchronous https://www.freecodecamp.org/news/nodejs-eventloop-tutorial/

  • Related