Express JavaScript Answers

How to Set the Response Header on Express.js Responses?

Spread the love

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) => {
      '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.

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 *