/

Working with HTTP Headers in Express

Working with HTTP Headers in Express

In this article, you will learn how to effectively work with HTTP headers using Express. HTTP headers play a crucial role in web communication as they contain important information about the request and response.

Accessing HTTP Header Values from a Request

To access all the HTTP headers of a request, you can utilize the Request.headers property. Here’s an example:

1
2
3
app.get('/', (req, res) => {
console.log(req.headers);
});

If you only need to access a specific header’s value, you can use the Request.header() method. Here’s an example:

1
2
3
app.get('/', (req, res) => {
const userAgent = req.header('User-Agent');
});

Changing HTTP Header Values for a Response

To change the value of any HTTP header in the response, you can make use of the Response.set() method. Here’s an example that demonstrates changing the Content-Type header to text/html:

1
res.set('Content-Type', 'text/html');

There is also a convenient shortcut specifically for setting the Content-Type header:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
res.type('.html');
// => 'text/html'

res.type('html');
// => 'text/html'

res.type('json');
// => 'application/json'

res.type('application/json');
// => 'application/json'

res.type('png');
// => 'image/png'

By utilizing the techniques mentioned above, you can effectively work with HTTP headers in Express. Understanding how to access and modify these headers will allow you to tailor the behavior of your web applications to meet specific requirements.

tags: [“Express”, “HTTP headers”, “Request.headers”, “Request.header()”, “Response.set()”, “Content-Type header”]