George Paouris
George Paouris

Reputation: 635

How to see the all the response headers in Node Express?

I want to see in Node Exprees enviroment all the headers that are sent to the client

headers

But when i see do this:

app.get("/", (req, res) => {
  console.log(res.getHeaders());
});

i only see this :

enter image description here

Upvotes: 1

Views: 3020

Answers (2)

jfriend00
jfriend00

Reputation: 707446

At the time you're looking at the outgoing headers, those are the only ones that have been added so far. The rest will be added by the code that sends the actual response or by other middleware.

If you want to see all the headers that were eventually added to the response before it was sent, you can monitor the finish event and THEN look at the headers:

app.use(function(req, res, next) {
    res.on('finish', () => {
        console.log(`request url = ${req.originalUrl}`);
        console.log(res.getHeaders());
    });
    next();
});

This will sometimes not include the date, content-type or content-length headers unless they are specifically set by the sending code. This is because if these are not set by the sending code, then the HTTP library adds these headers at a lower level as it is sending the headers and thus res.getHeaders() does not retrieve them and never knows about them.

Upvotes: 5

Matt Oestreich
Matt Oestreich

Reputation: 8528

Edit: I overlooked your first screenshot... Are you using any middleware? It looks like you're using the CORS middleware, at least - which is why you are showing more headers than the defaults..

It looks like Node/Express sends a Content-Length header when it can..

The Date header is mandatory per the HTTP spec, but it looks like you can change that behavior in Node/Express - I'm guessing by default Node/Express sets that value to true.

I did test setting res.sendDate = false and the date header was not sent, so it looks like that header is set by default for you, most likely as the last step in the response?


With res.sendDate = false;

enter image description here


Without setting res.sendDate (aka the default):

enter image description here


All in all, I'm assuming the headers you don't see when you console.log(res.getHeaders()) are set by Node/Express by default..

I wasn't able to find anything in the docs about default response headers (outside of the Date header), but it's possible I overlooked something. The Express docs don't have anything on it as they just use the built in http module from Node.

Upvotes: 2

Related Questions