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.

有帮助吗?

解决方案 2

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...

其他提示

In your main action, assign your json to an object on this (res is reserved):

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

Then you can access it in your after filter:

myController.after('myAction', function(next) {
      var model = this.model;
      console.log(model);
      next();
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top