3

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('/', (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.

1
  • 3
    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. Commented Nov 20, 2023 at 9:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

If I deploy it on example.com, will it work?
@HarshNarwariya I doubt you'd be able to deploy your app to example.com, but if you could it seems the code should work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.