jsonnode.jsexpresslocomotivejs

LocomotiveJS access response JSON in controller's after filter


I'm looking for a way to access the JSON being sent back to the requestor in the "after" filter for a controller.

var locomotive = require('locomotive');

var myController = new locomotive.Controller();

myController.after('myAction', function(next) {
    var response = {};      //I want to access the JSON being sent back in myAction: {'hello':'world'}
    console.log(response);  //this should log "{'hello':'world'}"
    next();
});

myController.myAction = function myAction() {
    this.res.json({'hello':'world'});
}

module.exports = myController;

If anyone has any way of doing this, it would be much appreciated.


Solution

  • I found a "hack" solution... It's not the cleanest, and requires changing the code within the express response.js file in "node_modules"...

    If anyone has a better option where you can access the json being sent in response to the request within the controller action (or controller filter) itself, I'd greatly appreciate it.

    Thanks.


    in the ~/node_modules/locomotive/node_modules/express/lib/response.js file, I altered the "res.json" function (line 174 for me) to include the following line after the declaration of the body variable (which is passed to the send function).

    this.responseJSON = body;
    

    This allows you to access this.responseJSON within a controller's after filter, as follows:

    myController.after('myAction', function(next) {
        **var response = this.res.responseJSON;      //ACCESS RESPONSE JSON HERE!!!!!**
        console.log(response);                     //Now logs "{'hello':'world'}"
        next();
    });
    

    Like I said, not the most elegant, but gets the job done in a pinch. Any more elegant solutions welcome...