English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Express.js Router is somewhat like nesting a small server within the server.
In the following example, we will use the router to create an API. The API is created separately to demonstrate modularization.
router1.js
var express = require('express') var router1 = express.Router() // Middleware specific to this router router1.use(function timeLog(req, res, next) { console.log('Requested URI Path: ', req.url) next() }) // Define the home page route router1.get('/', function(req, res) { res.send('Birds home page') }) // Define the route for about router1.get('/about', function(req, res) { res.send('About birds') }) module.exports = router1
We use express.Router() to create a router and then create some routing paths.
app.js
var express = require('express') var app = express() var router1 = require('/router1') app.use('/api/', router1) // Start Server var server = app.listen(8000, function(){ console.log('Listening on port 8000...') })
when we use app.use('/api/', router1all requests to the server with URI path,/api/ now are all routed to router1//localhost:8000/api/“1in the “ /”route. This is because forrouter1, http://localhost:8000/api/is considered as the basic path.
When you click on URI, http://localhost:8000/api/about/,/about/The selected route will be.
Terminal Log
On the first use, it may confuse you about the execution process. However, through practice, it can become a powerful tool for creating modular express applications.