How to get the hostname in Node.js Express
Learn, how to get the hostname or domain name of a current HTTP request in express.
Using req.hostname property
We can use the req.hostname
property to get the hostname from a current incoming request in express.
Example:
const express = require("express");
const app = express();
app.get("/users", (req, res) => {
console.log(req.hostname); // fun24.com
res.send('users');
});
If you need a port number along with the hostname, you can use the req.header('host')
method.
const express = require("express");
const app = express();
app.get("/users", (req, res) => {
console.log(req.hostname); // fun24.com:3900
res.send('users');
});