node express: how to find out if status will be 304 given etag

0

Issue

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

Solution

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.

Answered By – jfriend00

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More