Saturday, August 18, 2018

Call res callback in Express in addition to callback data

I have this code in my express controller file:

function logResponse(err, data) {
  if (err)
  {
    console.log('error name %s', err.name);
    console.log('error message %s', err);
  }

  console.log('\ndata: %s', JSON.stringify(data));

  res.status(200).send({
    'status'     : 'OK',
    'type'       : 'success',
    'message'    : 'User Info successfully fetched.',
    'data'       : JSON.stringify(data)
  });
}

// Get User Info through external API
exports.index = function(req, res) {
  privateClient.getUserInfo(logResponse, 'meMyselfAndIrene');
};

I get this to be expected error:

res.status(200).send({
     ^

TypeError: Cannot read property 'status' of undefined 

How do I define things in order for res to be available in logResponse? And how can I chain the callbacks in order to split up logging and http responding?

Solved

Simply passing as callback

function (err, data) { logResponse(err, res, data); }

will redirect res appropiately.


No comments:

Post a Comment