我试图将一些请求缓存到静态文件,这些文件可以由中间件直接由nginx提供.
核心代码:
function PageCache(config) {
config = config || {};
root = config.path || os.tmpdir() + "/_viewcache__";
return function (req, res, next) {
var key = req.originalUrl || req.url;
var shouldCache = key.indexOf("search") < 0;
if (shouldCache) {
var extension = path.extname(key).substring(1);
if (extension) {
} else {
if (key.match(/\/$/)) {
key = key + "index.html"
} else {
key = key + ".html";
}
}
var cacheFilePath = path.resolve(root + key)
try {
res.sendResponse = res.send;
res.send = function (body) {
res.sendResponse(body);
// cache file only if response status code is 200
cacheFile(cacheFilePath, body);
}
}
catch (e) {
console.error(e);
}
}
next()
}
}
Run Code Online (Sandbox Code Playgroud)
但是我发现无论状态代码如何都会缓存所有响应,而不应缓存代码为404,410,500或其他内容的响应.
但是我找不到任何api res.status或者res.get('status')可以用来获取当前请求的状态代码.
任何替代方案?
Muk*_*rma 19
您可以覆盖res.end响应结束时正在调用的事件.statusCode每当响应结束时,您都可以得到响应.
希望它能帮到你
var end = res.end;
res.end = function(chunk, encoding) {
if(res.statusCode == 200){
// cache file only if response status code is 200
cacheFile(cacheFilePath, body);
}
res.end = end;
res.end(chunk, encoding);
};
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11326 次 |
| 最近记录: |