NodeJS-express添加返回拦截器response interceptor

Express返回拦截器

有时候需要在express返回结果之前,自定义一些内容.所以可以定义一个全局处理器

方法

编写一个处理中间件

改写express自己的方法(res.write, res.end等等)

示例一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function modifyResponseBody(req, res, next) {
var oldWrite = res.write,
oldEnd = res.end;

var chunks = [];

res.write = function(chunk) {
chunks.push(chunk);

return oldWrite.apply(res, arguments);
};

res.end = function(chunk) {
if (chunk) chunks.push(chunk);

var body = Buffer.concat(chunks).toString('utf8');
console.log(req.path, body);

oldEnd.apply(res, arguments);
};

next();
}
module.exports = { modifyResponseBody };

示例二:

1
2
3
4
5
6
7
8
9
10
11
12
function modifyResponseBody(req, res, next) {
var oldSend = res.send;

res.send = function(data){
// arguments[0] (or `data`) contains the response body
arguments[0] = "modified : " + arguments[0];
oldSend.apply(res, arguments);
}
next();
}

module.exports = { modifyResponseBody };

然后在项目根文件引用

1
app.use(modifyResponseBody);

NOTE

  1. 如果使用了路由,需要引用在路由前面