Node.js 在express中间件中获取状态代码

Node.js 在express中间件中获取状态代码,node.js,express,Node.js,Express,我尝试将一些请求缓存到静态文件中,这些文件可以由nginx通过中间件直接提供服务 核心代码: function PageCache(config) { config = config || {}; root = config.path || os.tmpdir() + "/_viewcache__"; return function (req, res, next) { var key = req.originalUrl || req.url;

我尝试将一些请求缓存到静态文件中,这些文件可以由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()
    }
}
功能页面缓存(配置){
config=config |{};
root=config.path | | os.tmpdir();
返回函数(req、res、next){
var key=req.originalUrl | | req.url;
var shouldCache=key.indexOf(“搜索”)<0;
if(shouldCache){
var extension=path.extname(key).substring(1);
if(扩展){
}否则{
if(key.match(/\/$/)){
key=key+“index.html”
}否则{
key=key+“.html”;
}
}
var cacheFilePath=path.resolve(根+键)
试一试{
res.sendResponse=res.send;
res.send=函数(正文){
res.sendResponse(正文);
//仅当响应状态代码为200时缓存文件
cacheFile(cacheFilePath,body);
}
}
捕获(e){
控制台错误(e);
}
}
下一个()
}
}
然而,我发现所有的响应都被缓存,不管状态代码是什么,而使用代码404410500或其他东西的响应都不应该被缓存

但是我找不到任何api,如
res.status
res.get('status')
,可以用来获取当前请求的状态代码


任何替代解决方案?

您可以覆盖响应结束时调用的
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);
};

您可以使用res.statusCode来获取状态。

状态代码是为响应而指定的,而不是为请求而指定的,当您想要发送响应时,可以使用
res.status(404)。例如,发送(“确定”)
,这会有所帮助。为什么Express文档中没有
res.statusCode
?这就省去了我的麻烦…更新:出于某种原因,
res.statusCode
总是产生
200
,即使我的应用程序返回304或404。@odigity它对我有效。不过我使用了不同的实现:
res.status(404.send();if(res.headersSent)console.log(res.statusCode)
res.statusCode在中间件中始终返回200。@Jompis您可以使用express interceptor获取实际响应。您将看到res.statusCode具有实际的状态代码。