代码之家  ›  专栏  ›  技术社区  ›  Miguel Mesquita Alfaiate

在处理之后但在发送到客户端之前向所有响应添加头

  •  0
  • Miguel Mesquita Alfaiate  · 技术社区  · 8 年前

    我在node js应用程序中有两个端点:

    app.get('search', myGetController);
    app.post('add', myPostController);
    

    exports.myGetController = function(req, res) {
        res.status(404).json({ error: "not found" });
    };
    

    // process all responses to add ed25519
    app.use(function(req, res, next) {
        res.setHeader('CharCount', [How To get Body content]);
        next();
    });
    

    我有两个问题:

    首先,我想让我所有的控制器在处理后都经过这个中间件。

    第二,我想访问body内容,以便根据其内容生成一个header。

    更新

    这就是我所拥有的(在设置路线之前):

    app.use(function(req, res, next) {
        const oldResJson = res.json;
    
        res.json = function(body) {
            res.setHeader('myToken', generateHeaderBasedOnBody(oldResJson));
            oldResJson.call(res, body);
        }
    
        next();
    });
    

    传递给我的方法的响应是空字符串,即使服务发送的响应不是空的。我是在错误的地方做这件事,还是我错过了什么?

    1 回复  |  直到 8 年前
        1
  •  1
  •   Telokis    8 年前

    解决这个问题的一个方法是重写 res.json 功能如下:

    // process all responses to add ed25519
    app.use(function(req, res, next) {
        const oldResJson = res.json;
    
        res.json = function(body) {
            res.setHeader('CharCount', /* Use body here */);
            oldResJson.call(res, body);
        }
    
        next();
    });
    

    这样做,你甚至不需要改变你的控制器。

    推荐文章