Monday, 1 May 2017

Why is my return empty (Node.js, unirest)

I have a problem with my little Node.js test setup. I basically want an endpoint that I can call, and this endpoint can call different other endpoints and give me a JSON as a response. When I have a look at the console output of the performRequest function, everything looks good. But the return of this function doesn't get passed. I always get an empty {} as a response.

The routes.js that holds my routes:

var s24 = require("./s24");

var routes = function(app) {

  app.get("/ping", function(req, res) {
    res.send("<p>pong</p>");
    console.log("Received GET");
  });

  app.get("/getCategories", function(req, res) {
    var output = s24.getCategories();
    res.type('application/json');
    return res.send(output);
  });

};

module.exports = routes;

The s24.js that queries another REST-API:

var functions = require('./functions');

var appID = "XYZ";
var authorization = "ABC";

var getCategories = function () {
  var output = functions.performRequest("https://api.s24.com/v3/"+appID+"/categories", authorization);
  console.log(output);
  return output;
};

module.exports.getCategories = getCategories;

The functions.js that holds all my relevant functions:

var unirest = require('unirest');

var performRequest = function(endpoint,authorization,body) {
  unirest.get(endpoint)
  .headers({'Accept': 'application/json', 'Content-Type': 'application/json', 'Authorization': authorization})
  .send(body)
  .end(function (response) {
  var data = response.body;
  console.log(data);
  return data["id"];
  });
};

module.exports.performRequest = performRequest;



via Tom Meyer

No comments:

Post a Comment