Home  >  Article  >  Web Front-end  >  Detailed explanation of Node.js using Express.Router

Detailed explanation of Node.js using Express.Router

小云云
小云云Original
2017-12-21 10:45:063359browse

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 the method of using Express.Router in Node.js in detail. It 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 the async function in Node.js

PHP and Node.js

Node.JS related knowledge

The above is the detailed content of Detailed explanation of Node.js using Express.Router. 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