我在节点js app中有两个端点:
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();
});
我有两个问题:
首先,我想让我的所有控制器在处理后通过该中间件。
其次,我想访问正文内容,以便根据其内容生成标题。
UPDATE
我已经尝试过某人发布的建议答案,但它无法正常工作,或者我遗漏了一些东西。
这就是我所拥有的(在设置我的路线之前):
app.use(function(req, res, next) {
const oldResJson = res.json;
res.json = function(body) {
res.setHeader('myToken', generateHeaderBasedOnBody(oldResJson));
oldResJson.call(res, body);
}
next();
});
传递给我的方法的响应是一个空字符串,即使服务发送的响应不为空。我是在错误的地方做这个,还是我错过了什么?
这个问题的一个解决方案是覆盖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();
});
通过这样做,您甚至不需要更改控制器。