0

So I am building an application in Node.js and express, where I have a router and API module, from which I make HTTP request. I am struggling with wrapping my head around passing values between callbacks.

It looks like this:

Router:

var dataAPI = require('../API/getData');
var express = require('express');
var router = express.Router();

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

module.exports = router;

And the getAPI file has this function:

var request = require('request');
var config = require('../config/config');

getData = function(callback){
    request({
        headers: {
            'Content-Type' : 'application/json',
            'Authorization' : config.authorization.token
        },
        uri: config.url.get_portfolio,
        method: 'GET',
        rejectUnauthorized: false,
    }, function(err, res, body){
        if (err || body == undefined ){
            console.log("Error in first callback.");
            throw err;
        } 
        console.log("HTTP: ", res.statusCode, " GOT DATA: ", body);
    });
}

What I want to accomplish here is to be able to do

res.render('index', {data }) 

And use the data from request made in getData function. What is the correct way to do that?

1 Answer 1

1

you have not used callback in request made by getData function and the callback parameters are incorrect try doing this:

var dataAPI = require('../API/getData.js')
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) { 
        dataAPI.getData(function(err,data){
                if(err) throw err;
                res.render('index', {data: data});
        });
});

//getData.js file

var request = require('request');
var config = require('../config/config');

exports.getData = function(callback){
    request({
        headers: {
            'Content-Type' : 'application/json',
            'Authorization' : config.authorization.token
        },
        uri: config.url.get_portfolio,
        method: 'GET',
        rejectUnauthorized: false,
    }, function(err, res, body){
        if (err || body == undefined ){
            console.log("Error in first callback")
            callback(new Error("Error in first callback."),null) <----------
        }else{
            console.log("HTTP: ", res.statusCode, " GOT DATA: ", body);
            callback(null,body) <--------------
        }
    });
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, that worked. Your answer explained something I couldn't get for a while!

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.