栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

与Express.js嵌套路由器一起休息

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

与Express.js嵌套路由器一起休息

您可以通过将路由器作为中间件附加到其他路由器上(带有或不带有)来嵌套路由器

params

{mergeParams: true}
如果
params
要从父路由器访问,则必须传递到子路由器。

mergeParams
在Express
4.5.0
中引入(2014年7月5日)

在此示例中,路线上的

itemRouter
附加到
userRouter``/:userId/items

这将导致以下可能的路线:

GET /user
->
hello user

GET /user/5
->
hello user 5

GET /user/5/items
->
hello items from user 5

GET /user/5/items/6
->
hello item 6 from user 5

var express = require('express');var app = express();var userRouter = express.Router();// you need to set mergeParams: true on the router,// if you want to access params from the parent routervar itemRouter = express.Router({mergeParams: true});// you can nest routers by attaching them as middleware:userRouter.use('/:userId/items', itemRouter);userRouter.route('/')    .get(function (req, res) {        res.status(200) .send('hello users');    });userRouter.route('/:userId')    .get(function (req, res) {        res.status(200) .send('hello user ' + req.params.userId);    });itemRouter.route('/')    .get(function (req, res) {        res.status(200) .send('hello items from user ' + req.params.userId);    });itemRouter.route('/:itemId')    .get(function (req, res) {        res.status(200) .send('hello item ' + req.params.itemId + ' from user ' + req.params.userId);    });app.use('/user', userRouter);app.listen(3003);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/484607.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号