上QQ阅读APP看书,第一时间看更新
How to do it...
Suppose that you want to write a modular mini-application within your ExpressJS main application that can be mounted to any URI. You want to be able to choose the path where to mount it, or you just want to mount the same route methods and handlers to several others paths or a URI.
- Create a new file named modular-router.js
- Initialize a new ExpressJS application:
const express = require('express') const app = express()
- Define a router for your mini-application and add a request method to handle requests for path "/home":
const miniapp = express.Router() miniapp.get('/home', (request, response, next) => { const url = request.originalUrl response .status(200) .send(`You are visiting /home from ${url}`) })
- Mount your modular mini-application to "/first" path, and to "/second" path:
app.use('/first', miniapp) app.use('/second', miniapp)
- Listen for new connections on port 1337:
app.listen( 1337, () => console.log('Web Server running on port 1337'), )
- Save the file
- Open a Terminal and run the following command:
node modular-router.js
- To see the results, navigate in your web browser to:
http://localhost:1337/first/home
http://localhost:1337/second/home
You will see two different outputs:
You are visting /home from /first/home You are visting /home from /second/home
As can be seen, a router was mounted to two different mount points. Routers are usually referred to as mini-applications because they can be mounted to an ExpressJS application's specific routes and not only once but also several times to different mount points, paths, or URIs.