I’ve implemented a simple Express.js application that extracts the predomain from incoming requests’ hostnames. The code seems to be functioning correctly when I use localhost:3000, but it fails when I try 127.0.0.1:3000.
Here’s a snippet of the code I’m using:
const express = require('express');
const app = express();
app.use((req, res, next) => {
const parts = req.hostname.split('.');
req.predomain = parts[0];
next();
});
app.get("https://stackoverflow.com/", (req, res) => {
res.json({ predomain: req.predomain });
});
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
When I access http://harsh.localhost:3000, the API correctly returns the predomain as expected (harsh). However, when I access http://harsh.127.0.0.1:3000 the postman or chrome cannot find the address itself. I’m curious as to why this might be happening and how I can modify my code to correctly handle the extraction of the predomain even when using 127.0.0.1 or something else.
The issue here is conceptual, not with your code – unlike a domain that may have subdomains, an IP (v4) address is always four integers delimited by dots. You simply can’t add a subdomain to an IP address.
A IP Address (127.0.0.1) is not the same as a Domain name (example.com / foo.example.com) A IP Address can not have/be treated the same as a domain/sub domain.