Use HTTP headers in Express

Learn how to use Express to access and change HTTP headers

Access HTTP header value from request

You can use to access all HTTP headersRequest.headersproperty:

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

useRequest.header()Ways to access a single request header value:

app.get('/', (req, res) => {
  req.header('User-Agent')
})

Change any HTTP header value of the response

You can change any HTTP header value usingResponse.set():

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

However, there is a shortcut for the Content-Type header:

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:

Download mine for freeExpress.js manual


More crash tutorials: