How can I find out if the response status will be 304 (Not-Modified) because of etag value received inside If-None-Match header? I want to log this information but cannot get it in the node server. Seems express handles this by itself:
https://expressjs.com/en/api.html#express.static
CodePudding user response:
Express, gets its express.static()
from the serve-static
module. That module calls the send
module from here and that module uses the fresh
module from here which is where it seems to test the eTag here.
Here's the fresh()
function:
function fresh (reqHeaders, resHeaders) {
// fields
var modifiedSince = reqHeaders['if-modified-since']
var noneMatch = reqHeaders['if-none-match']
// unconditional request
if (!modifiedSince && !noneMatch) {
return false
}
// Always return stale when Cache-Control: no-cache
// to support end-to-end reload requests
// https://tools.ietf.org/html/rfc2616#section-14.9.4
var cacheControl = reqHeaders['cache-control']
if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
return false
}
// if-none-match
if (noneMatch && noneMatch !== '*') {
var etag = resHeaders['etag']
if (!etag) {
return false
}
var etagStale = true
var matches = parseTokenList(noneMatch)
for (var i = 0; i < matches.length; i ) {
var match = matches[i]
if (match === etag || match === 'W/' etag || 'W/' match === etag) {
etagStale = false
break
}
}
if (etagStale) {
return false
}
}
// if-modified-since
if (modifiedSince) {
var lastModified = resHeaders['last-modified']
var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince))
if (modifiedStale) {
return false
}
}
return true
}
To call fresh()
yourself to get this value on your own, you would have to be able to pass it the exact headers that serve-static
and then send
would pass it. It's probably doable, but you'd have to trace through how express-static()
and send()
are setting up the response headers before passing them to fresh()
.
FYI, this begs the question of "why" are you trying to do this? What problem are you trying to solve? Perhaps there is a better way to solve the real problem. As your question stands now, it's a bit of an XY problem where you've asked a question about your attempted solution to some problem without telling us what the actual problem is. There may be a better/easier solution to the actual problem.
CodePudding user response:
If all you're trying to do is to log the final status code after the response is sent, you can listen for the finish
event and then examine res.statusCode
. Here's a simple example:
const express = require('express');
const app = express();
app.get("/", (req, res) => {
res.sendFile("temp.html", { root: __dirname });
res.on('finish', () => {
console.log(`finish event: ${res.statusCode}`);
});
});
app.listen(80);
Running this server and then requesting /
the first time logs 200, the second time logs 304.