带有子路由器的Express路由器 [英] Express Router with a sub-router

查看:164
本文介绍了带有子路由器的Express路由器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说父模块有一个使用公共请求的路由器

Let's say parent module has a router with public requests using

父模块

app.get("/speakers",...
app.get("/agenda",... etc.

和另一条通配符路由,该路由实际上将请求委托给子模块,以处理父模块不需要知道的所有嵌套操作

and another wild card route which actually delegates the request to child module to handle all of it's nested operations which parent module doesn't need to know or care about.

app.all("/admin/*/*" //delegates task to another module

子模块

子模块接收到管理请求,但随后必须处理所有uri,路线和参数

child module receives the admin request but then it has to deal with all uri's, routes and params

like

/admin/login
/admin/dashboard/events
/admin/dashboard/events/1 //could go deeper

如何在此嵌套级别上进行另一级的路由解析或引擎?

How to have another level of route parsing or engine at this nested level?

推荐答案

您可以组织您的管理路线s作为单独的模块,例如:

You can organize your admin routes as a separate module like this:

/routes/admin.js

var login = function(req, res, next) {
    res.end();
}

// etc...

module.exports = express.Router()
    .post('/login', login)
    .get('/dashboard/events', listEvents)
    .get('/dashboard/events/:id', findEvent);

然后在您的 app.js 中:

var admin = require('./routes/admin');
app.use('/admin', admin);

请注意,您在管理路由中定义的路由都将相对于您指定的根目录作为 app.use 的第一个参数。

Note that the routes you defined in the admin route are all going to be relative to the root you specified as the first param to app.use.

这篇关于带有子路由器的Express路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆