hguser
hguser

Reputation: 36068

Get status code in express middleware

I tried to cache some request to static files which can be served by nginx directly by middleware.

Core codes:

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()
    }
}

However I found that all the response are cached no matter the status code, while respone with code 404,410,500 or something else should not be cached.

But I can not find any api like res.status or res.get('status') which can be used to get the status code of the current request.

Any alternative solution?

Upvotes: 20

Views: 31637

Answers (3)

Abkreno
Abkreno

Reputation: 173

You can use on-finished middleware to make sure response headers are sent and then read the status

var onFinished = require('on-finished')


onFinished(res, function (err, res) {
   // read res.statusCode here
})

Upvotes: 1

Hasan Zahran
Hasan Zahran

Reputation: 1452

you can use res.statusCode to the get the status.

Upvotes: 1

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

You can override res.end event that is being called whenever response ends. You can get statusCode of response whenever response ends.

Hope it helps you

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);
};

Upvotes: 36

Related Questions