- MERN Quick Start Guide
- Eddy Wilson Iriarte Koroliova
- 304字
- 2021-06-25 21:30:15
There's more...
It is possible to pass control back to the next middleware function or route method outside of a router by calling next('router').
router.use((request, response, next) => { next('route') })
For example, by creating a router that expects to receive a user ID as a query parameter. The next('router') function can be used to get out of the router or pass control to the next middleware function outside of the router when a user ID is not provided. The next middleware function out of the router can be used to display other information when the router passes control to it. For example:
- Create a new file named router-level-control.js
- Initialize a new ExpressJS application:
const express = require('express') const app = express()
- Define a new router:
const router = express.Router()
- Define our logger middleware function inside the router:
router.use((request, response, next) => { if (!request.query.id) { next('router') // Next, out of Router } else { next() // Next, in Router } })
- Add a route method to handle GET requests for path "/" which will be executed only if the middleware function passes control to it:
router.get('/', (request, response, next) => { const id = request.query.id response.send(`You specified a user ID => ${id}`) })
- Add a route method to handle GET requests for path "/" outside of the router. However, include the router as a route handler as the second argument, and another route handler to handle the same request only if the router passes control to it:
app.get('/', router, (request, response, next) => { response .status(400) .send('A user ID needs to be specified') })
- Listen on port 1337 for new connections:
app.listen( 1337, () => console.log('Web Server running on port 1337'), )
- Save the file
- Open a terminal and run:
node router-level-control.js
- To see the result, in your browser, navigate to:
http://localhost:1337/ http://localhost:1337/?id=7331