我尝试通过中间件将一些请求缓存到静态文件中,这些文件可以直接由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()
}
}
然而,我发现所有响应都被缓存了,无论状态码如何,而状态码为404、410、500或其他的响应不应该被缓存。
但是我找不到任何像res.status
或res.get('status')
这样的API,可以用来获取当前请求的状态码。
是否有任何替代方案?
res.status(404).send("ok")
作为示例。 - farhadamjady