Categories
Express JavaScript Answers

How to Get the Hostname of the Current Request in Express?

Spread the love

To get the hostname of the current request in Express, we can use the req.headers.host property.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send(req.headers.host);
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

to return the hostname of the client that made the request as the response for the / route.

The hostname is a string.

Therefore, when we go to / , we see the hostname of the client that made the request returned.

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 *