Detailed explanation of Node.js using Express.Router

小云云
Release: 2017-12-21 10:45:06
Original
3311 people have browsed it

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
Copy after login

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
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!