0

我正在寻找一种方法来访问在控制器的“之后”过滤器中发送回请求者的 JSON。

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;

如果有人有任何方法可以做到这一点,将不胜感激。

4

2 回答 2

0

在您的主要操作中,将您的 json 分配给此对象(保留 res):

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

然后你可以在你的后过滤器中访问它:

myController.after('myAction', function(next) {
      var model = this.model;
      console.log(model);
      next();
});
于 2014-05-14T02:43:29.810 回答
0

我找到了一个“hack”解决方案......它不是最干净的,并且需要更改“node_modules”中的 express response.js 文件中的代码......

如果有人有更好的选择,您可以访问响应控制器操作(或控制器过滤器)本身中的请求而发送的 json,我将不胜感激。

谢谢。


在 ~/node_modules/locomotive/node_modules/express/lib/response.js 文件中,我更改了“res.json”函数(对我来说是第 174 行),在 body 变量的声明(通过到发送功能)。

this.responseJSON = body;

这允许您在控制器的后过滤器中访问 this.responseJSON,如下所示:

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

就像我说的,不是最优雅的,但可以在紧要关头完成工作。欢迎任何更优雅的解决方案......

于 2014-05-28T14:18:56.360 回答