To set the response header on express.js responses, we can call the res.set
method with the response header content.
For instance, we can write:
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res
.set({
'Content-Type': 'text/plain',
'Content-Length': '123',
'ETag': '12345'
})
.send('hello world');
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
to call the set
method in the /
route with an object that has the response header keys and values.
The property names are the keys and the property values are the values.
Then we can also call send
with the response body we want to return.
Therefore, when we make a request to the /
route, we should see hello world
in the response body and the object’s content in the response header.