There's more...

vhost adds a vhost object to the request object, which contains the complete hostname (displaying the hostname and port), hostname (without the port), and matching strings. These give you more control in how to handle virtual domains.

For example, we could write an application that allows users to have their own sub-domain with their name:

  1. Create a new file named user-subdomains.js
  2. Include the vhost NPM module. Then, initialize a new ExpressJS application:
      const express = require('express') 
      const vhost = require('vhost') 
      const app = express() 
  1. Define a new router. Then, add a route method to handle GET requests on path "/". Use the vhost object to access the array of subdomains:
       const users = express.Router() 
       users.get('/', (request, response, next) => { 
        const username = request 
            .vhost[0] 
            .split('-') 
            .map(name => ( 
                name[0].toUpperCase() + 
                name.slice(1) 
             )) 
            .join(' ') 
        response.send(`Hello, ${username}`) 
     }) 
  1. Mount the router:
       app.use(vhost('*.localhost', users)) 
  1. Listen on port 1337 for new connections:
      app.listen( 
           1337, 
          () => console.log('Web Server running on port 1337'), 
      ) 
  1. Save the file
  2. Open a terminal and run:
      node user-subdomains.js 
  1. To see the result, in your web browser, navigate to:
        http://john-smith.localhost:1337/
        http://jx-huang.localhost:1337/
        http://batman.localhost:1337/
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.8.216