【发布时间】:2015-07-16 06:29:08
【问题描述】:
我正在尝试使用 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。这当然会导致无限循环。 但我真的找不到任何解决方案。
【问题讨论】:
标签: node.js express middleware