is there a way to use the express router to get the variable of the subdomain.
Lets say I have foo.example.com
how can I get an output of foo
.
Thanks
In Express 4.x you can use req.subdomains
property.
// Host: "tobi.ferrets.example.com"
req.subdomains
// => ["ferrets", "tobi"]
ref.: https://expressjs.com/en/4x/api.html#req.subdomains
Express 4.x comes req.subdomains but if you are using older version or want to play your own code then can be used other framework as well then you may like
var app = express();
app.use(function(req, res, next) {
var host = req.get('host');
console.log(getSubdomain(host));
console.log(getSubdomainList(host));
next();
})
function getSubdomain(host) {
var subdomain = host ? host.substring(0, host.lastIndexOf('.')) : null;
return subdomain;
}
function getSubdomainList(host) {
var subdomainList = host ? host.split('.') : null;
if(subdomainList)
subdomainList.splice(-1, 1);
return subdomainList;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With