Categories
JavaScript Answers

How to get HTTP headers with Node.js?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *