EXPRESS的router对象使用实例讲解
程序员文章站
2022-04-04 21:35:19
router对象:
1.充当子路由
var express = require("express");
var app = express();
v...
router对象:
1.充当子路由
var express = require("express"); var app = express(); var router = express.Router(); router.get('/test',function(req,res,next){ res.send('test') }); app.use('/user/:name',router); app.listen(3000);
当访问https://localhost:3000/user/jack/test时,页面显示test
router.get('/test',function(req,res,next){ res.send('test') });//是一个子路由,相对于/user/:name,这是因为app.use('/user/:name',router);
var express = require("express"); var app = express(); var router = express.Router(); router.get('/test',function(req,res,next){ res.send(req.params.name) }); app.use('/user/:name',router); app.listen(3000);
当访问https://localhost:3000/user/jack/test时,页面没有内容,这是因为父级路由没有合并到子级路由,
var router = express.Router({
mergeParams:true
});父级路由合并到子级路由
var express = require("express"); var app = express(); var router = express.Router({ mergeParams:true }); router.get('/test',function(req,res,next){ res.send(req.params.name) }); app.use('/user/:name',router); app.listen(3000);
当访问https://localhost:3000/user/jack/test时,页面显示jack
当访问https://localhost:3000/user/jack/Test时,页面显示jack
test中字母的大小写没有区分,若要区分子路由中的大小写
2.路径大小写:
var express = require("express"); var app = express(); var router = express.Router({ mergeParams:true, caseSensitive:true }); router.get('/test',function(req,res,next){ res.send('test') }); router.get('/Test',function(req,res,next){ res.send('Test') }); app.use('/user/:name',router); app.listen(3000);
访问https://localhost:3000/user/jack/Test 页面显示Test
访问https://localhost:3000/user/jack/test 页面显示test
3.严格路径:
var express = require("express"); var app = express(); var router = express.Router({ }); router.get('/test',function(req,res,next){ res.send('test') }); app.use('/user/:name',router); app.listen(3000);https://localhost:3000/user/jack/test
https://localhost:3000/user/jack/test/
访问上面的两个网址结果相同,若要区分上面的两个网址,就要使用
var router = express.Router({
strict:true
});
二.
var router = express.Router({ mergeParams:true, caseSensitive:true, strict:true });//只是针对router对象下的路径
app下的路由如果要设置,则
app.set('strict routing',true); app.set('case sensitive',true);
上一篇: 年货大集来袭,2000元档手机推荐
下一篇: 去总公司开会