Matt Leach Matt Leach - 4 months ago 8
Node.js Question

NodeJS passing results form HTTPS request to the view

I am making an HTTPS request to an API (wrike.com) and everythings working except I'm struggling to pass the result to my view in order to display in the frontend.

This is the function code:

module.exports.getWrikeFolder = function(user, callback) {
User.findOne({email: user}, function(err, doc){
if(err) throw err;
var accessToken = doc.wrikeaccess;
console.log(accessToken);

var data = querystring.stringify({
"descendants": true,
"project": false
});

var options = {
host: 'www.wrike.com',
method: 'GET',
path: '/api/v3/folders/',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'bearer ' + accessToken
}
}

var folders = [];

var request = https.request(options, function(res) {
res.on('data', function (chunk) {
folders.push(chunk);
}).on('end', function() {
folders = Buffer.concat(folders).toString();
console.log(folders);
});

});

request.on('error', function(e) {
console.log('problem with request: ' + e.message);
});

request.write(data);
request.end(err, folders);
});
}


And this is the code for the route:

router.get('/dmd', ensureAuthenticated, function(req, res, next) {
wrike.getWrikeFolder(user, function(err, folders) {
//if(err) throw err;
res.render('dmd-codes', {
title: 'DMD Codes',
nav: 'Admin',
folders: folders
});
});
});


I know the function works as the
console.log(folders);
line shows the expected result in the console. What am I missing to get the result into the route.

Thanks for any help.

Answer

Looks like you never execute your callback in the module that does the http request to the API, which means the res.render() wouldn't execute. Try adding the execution of callback inside of getWrikeFolder():

module.exports.getWrikeFolder = function(user, callback) {
  User.findOne({email: user}, function(err, doc){
    // if(err) throw err; // NOOOO! Use callbacks ;)
    if (err) return callback(err);

    // ... (your code)

    var request = https.request(options, function(res) {
      res.on('data', function (chunk) {
        folders.push(chunk);
      }).on('end', function() {
        folders = Buffer.concat(folders).toString();
        console.log(folders);

        // make sure to execute callback!
        callback(null, folders);

      });

    });

    request.on('error', function(e) {
      console.log('problem with request: ' + e.message);
      // don't forget to use the callback!!
      return callback( new Error('problem with request: ' + e.message) );
    });

    request.write(data);
    request.end(err, folders);
  });
}
Comments