Modular route handlers
ExpressJS has a built-in class called router. A router is just a class that allows developers to write mountable and modular route handlers.
A Router is an instance of ExpressJS' core routing system. That means, all routing methods from an ExpressJS application are available:
const router = express.Router() router.get('/', (request, response, next) => { response.send('Hello there!') }) router.post('/', (request, response, next) => { response.send('I got your data!') })
Getting ready
In this recipe, we will see how to use a router to make a modular application. Before you start, create a new package.json
file with the following content:
{ "dependencies": { "express": "4.16.3" } }
Then, install the dependencies by opening a terminal and running:
npm install
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...