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?
In express, we can use res. status(–statusCode–) to set the status code. Let's create a simple web application using express and create a blog route, and when the user tries to access that route it will send the status code.
Middleware functions are functions that have access to the request object ( req ), the response object ( res ), and the next function in the application's request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Methods to Set HTTP Status Code Sr.No. This method sets an arbitrary status code. The setStatus method takes an int (the status code) as an argument. If your response includes a special status code and a document, be sure to call setStatus before actually returning any of the content with the PrintWriter.
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);
};
you can use res.statusCode to the get the status.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With