Node learning (2) using express to set the route

1, Common way

The most direct and simple way is to set each path to be accessed one by one

var express=require('express');
var app=express();
//Main page
app.get('/',function(req,res){
	res.end('<h1>Admin page</h1>')
})
//Subpage one
app.get('/one',function(req,res){
	res.end('<h1>One page</h1>')
})
//Subpage two
app.get('/two',function(req,res){
	res.end('<h1>Two page</h1>')
})
//Subpage two subpage three below
app.get('/two/three',function(req,res){
	res.end('<h1>Three page</h1>')
})

var server=app.listen(3000)

2, Encapsulate each path and mount it according to requirements, which can be understood as componentization

var express=require('express');
var app=express();
var admin=express();
var one=express();
var two=express();
var three=express();
var four=express();

admin.get('/',function(req,res){
	res.send('Admin page')
})

one.get('/',function(req,res){
	res.send('One page')
})

two.get('/',function(req,res){
	res.send('Two page')
})

three.get('/three',function(req,res){
	res.send('Three page')
})
four.get('/',function(req,res){
	res.send('Four page')
})

app.use('/',admin);//Access localhost:3000 / output Admin page
app.use('/one',one);//Visit localhost:3000/one to output One page
app.use('/two',two);//Visit localhost:3000/two to output two pages

app.use(['/one','/two'],three);//Visit localhost:3000/one/three or localhost:3000/two/three to output Three page
one.use('/',four)//Visit localhost:3000/one/four to output Four page

var server=app.listen(3000)


There are two ways to set sub routes:

1) Directly through the named route setting, i.e. setting multi-layer sub paths in the outermost path

Such as app,use('/one/two/three/...',router)

2) Set the next level path for the encapsulated self route

For example, app. Use ('/ parent', router [parent);

router_parent.use('/son,router_son)


Posted by wizkid on Fri, 01 May 2020 20:11:49 -0700