我正在尝试使用express中间件实现一些缓存,这似乎很好用,但是我在某处陷入了无限循环。
在我的路由器中,我有以下路由:
router.get('/test', [middleware.cache.cache('1 day', true), controllers.test]);
中间件middleware.cache.cache的结构如下所示:
module.exports.cache = function(time, global) {
// Do some stuff with the time here
return function cache(req, res, next) {
// Keep a copy of the actual send method
res._send = res.send;
// Overwrite the res.send function
res.send = function(obj) {
console.log('[' + res.statusCode + '] Cache: ' + redisKey);
// Get the key from redis
redis.get(redisKey)
.then(function(result) {
result = JSON.parse(result);
if(!_.isNull(result)) {
console.log('Expired cache found');
// Send initial object
return res._send(obj);
} else {
console.log('Cache found');
// Send back cached object
return res._send(result.obj);
}
} else {
console.log('No data found');
storeInRedis(redisKey, obj, time);
// Send initial object
return res._send(obj);
}
})
.fail(function(err) {
console.log(err);
return res._send(obj);
});
};
next();
};
};
我得到的输出结果如下所示:
[200] Cache: cache_global_test
Cache found
[200] Cache: cache_global_test
Cache found
...
我怀疑当我调用res._send(obj)时,它实际上是指我刚刚覆盖的原始res.send。这当然会导致无限循环。但我真的找不到任何解决方案。
tamper
和express-interceptor
。 - robertklep