How to get HTTP headers with Node.js?

Sometimes, we want to get HTTP headers with Node.js.

In this article, we’ll look at how to get HTTP headers with Node.js.

How to get HTTP headers with Node.js?

To get HTTP headers with Node.js, we can use the res.headers properties.

For instance, we write

const http = require("http");
const options = {
  method: "HEAD",
  host: "example.com",
  port: 80,
  path: "/",
};
const req = http.request(options, (res) => {
  console.log(JSON.stringify(res.headers));
});
req.end();

to call http.request to make a request.

We call it with the request options object and a callback that runs when the response is received.

Then we get the response headers for the request with res.headers.

Conclusion

To get HTTP headers with Node.js, we can use the res.headers properties.