Express.js – req.subdomains Property


req.subdomains returns an array of all the subdomains in the domain name of the request. The application property subdomain offset is used for determining the beginning of the subdomain segments. The default value of the subdomain offset property is 2.

Syntax

req.subdomains

Example

Create a file with the name "reqSubdomains.js" and copy the following code snippet. After creating the file, use the command "node reqSubdomains.js" to run this code as shown in the example below −

// req.subdomains Property Demo Example
// Importing the express
var express = require('express');

// Initializing the express and port number
var app = express();

// Initializing the router from express
var router = express.Router();
var PORT = 3000;

// Defining an endpoint
app.get('/api', function (req, res) {
   console.log(req.subdomains);
   res.send(req.subdomains);
});
app.listen(PORT, function(err){
   if (err) console.log(err);
   console.log("Server listening on PORT", PORT);
});

Output

Hit the following Endpoint with a GET request: localhost:3000/api

C:\home
ode>> node reqSubdomains.js Server listening on PORT 3000 []

If the host address is something like this: "hello.tutorials.point.com", then the req.subdomains returns it as an array −

['hello', 'tutorials', 'point']

Updated on: 06-Apr-2022

354 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements