Home >Web Front-end >JS Tutorial >Detailed explanation of using Express.Router instance in Node.js

Detailed explanation of using Express.Router instance in Node.js

小云云
小云云Original
2018-01-19 11:03:321915browse

In actual development, there are usually dozens or even hundreds of routes, all written in index.js, which is bloated and difficult to maintain. In this case, express.Router can be used to implement a more elegant routing solution. This article mainly introduces in detail how to use Express.Router in Node.js , has certain reference value, interested friends can refer to it, I hope it can help everyone.

The directory structure is as follows:

routes’ index.js code is as follows:


const express = require('express')
const router = express.Router()

router.get('/', function (req, res) {
 res.send('hello, express')
})

module.exports = router

routes The users.js code is as follows:


const express = require('express')
const router = express.Router()

router.get('/:name', function (req, res) {
 res.send('hello, ' + req.params.name)
})

module.exports = router

The main index.js code is as follows:


const express = require('express');
const app = express()
const indexRouter = require('./routes/index');
const userRouter = require('./routes/users');

app.use('/', indexRouter);
app.use('/users', userRouter);

app.listen(3000);

Browser access request :

Each routing file generates an express.Router instance router and exports it, and mounts it to a different path through app.use .

In actual development, it is recommended to use express.Router to separate different routes into different routing files.

Related recommendations:

How to use router in vue-cli

vue-router implements tab label page

Detailed explanation of vue-router routing and navigation between pages

The above is the detailed content of Detailed explanation of using Express.Router instance in Node.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn