Search code examples
javascriptexpresspugunirest

Send response from Unirest Node get request function to Jade view


I am in the process of building my first Node app, and I am having troubles with unirest.get requests. My project is built using Node, Express, Node and the Act On API.

I am using the express generator to get the project of the ground quickly.

The problem I am experiencing is that I am struggling to get the response through to my route file. I am requesting a list from the Act On API which is returning correctly as I can see the response in the console when I log it, but cannot get the data through to the templates.

function getTheList(callback) {
var Request = unirest.get('https://restapi.actonsoftware.com/api/1/list/l-0001')
.headers({
    'Accept': 'application/json',
    'Authorization': 'Bearer ' + access_token
})
.query({
    "count": 20,
    "fields": "First Name;Last Name;Email;"
})
.end(function(response, error) {
    var data = response.body.data;
    if (!error && response.statusCode == 200) {
        callback(returnData(data)); 
    } else {
        console.log('Failed response');
    }
});
}

function returnData(theData){
  console.log(theData);
  return theData;
}

module.exports.get = getTheList;

And the code inside my routes file to get this information.

var masterList = require('../acton/getMasterList');

var myListVar = masterList.get();

Any help on what I am doing wrong would be greatly appreciated.


Solution

  • The getTheList function that you describe expects a callback which you don't provide when you call it like so masterList.get().

    So you can either do something like:

    masterList.get(function(data){
        //you can access data here.
    })
    

    Or, in the getTheList implementation just do away with the callback entirely.

     .end(function(response, error) {
        var data = response.body.data;
        if (!error && response.statusCode == 200) {
          returnData(data); //Just do this may be.
        } else {
          console.log('Failed response');
        }
    });