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.