Search code examples
javascriptnode.jshandlebars.js

REST Call within node.js express from js file in route directory


I am trying to make a call to a REST call to an API and display the returned data on the view but my current code doesn't seem to be working. I am very new to node.js so I would really appreciate some help.

Here is what index.js looks like:

var router = require('express').Router();

function GetCompanyInformation() {
    var request = require('request');
    request('http://table.finance.yahoo.com/table.csv?s=orcl&a=0&b1&c=2010&d=0&e=1&f=2011&g=d&y=0&z=orcl', function (error, response, data) {
        if (!error && response.statusCode == 200) {
            return data;
        }
        return 'An error has occurred.'
    })
}

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('index', {
        title: 'Express',
        data : GetCompanyInformation()
    });
});

module.exports = router;

Here is my view index.hbs (handlebars):

<h1>{{ title }}</h1>
<h1>{{ data }}</h1>

Title is coming back fine. I am just not sure how to pass the data from the rest call. Or if i am even doing it correctly. My main goal is make a rest call and place the returned data in an array and then pass the array to the view.

I added a yahoo finance rest call just for an example.

Any help is much appreciated!


Solution

  • welcome to Nodejs , everything here is Asynchronous ,it means that you have to wait to your function finish before do something , usually we use a callback style (other options are promises for example) , code example :

    function GetCompanyInformation(callback) {
        var request = require('request');
        request('http://table.finance.yahoo.com/table.csv?s=orcl&a=0&b1&c=2010&d=0&e=1&f=2011&g=d&y=0&z=orcl', function (error, response, data) {
            if (!error && response.statusCode == 200) {
                return callback(null,data);
            }
            return callback('An error has occurred.',null);
        })
    }
    
    /* GET home page. */
    router.get('/', function(req, res, next) {
        GetCompanyInformation(function(err,data){
            //if(err) Manage error ; console.log(err)
            //else
            console.log(data)
            res.render('index', {
              title: 'Express',
              data : data
            });
        });
    });