建议采用:集中式路由,
不要把路由规则逻辑散落在多个地方,会给排查问题带来困扰
路由分组
路由拆分,路由映射 app/router/user.js
/**
* User: lulongwen
* Date: 2021-06-20 18:28
* Description:
*/
'use strict';
module.exports = app => {
const { router, controller } = app;
console.log('router-child', router);
router.get('/api/users', controller.user.index);
};
router.js
app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
* app 就是 Egg的实例
*/
module.exports = app => {
const { router, controller } = app;
require('./router/user')(app);
router.get('/404.html', controller.error.notFound);
};
router拆分路由
app/router.js
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
require('./router/home')(app);
require('./router/news')(app);
require('./router/admin')(app);
};
router/*
// app/router/news.js
module.exports = app => {
app.router.get('/news/list', app.controller.news.list);
app.router.get('/news/detail', app.controller.news.detail);
};
// app/router/admin.js
module.exports = app => {
app.router.get('/admin/user', app.controller.admin.user);
app.router.get('/admin/log', app.controller.admin.log);
};
路由重定向
路由内部重定向
// app/router.js
module.exports = app => {
app.router.get('index', '/home/index', app.controller.home.index);
app.router.redirect('/', '/home/index', 302);
};
// app/controller/home.js
exports.index = async ctx => {
ctx.body = 'hello controller';
};
// curl -L http://localhost:7001
外部重定向
// app/router.js
module.exports = app => {
app.router.get('/search', app.controller.search.index);
};
// app/controller/search.js
exports.index = async ctx => {
const type = ctx.query.type;
const q = ctx.query.q || 'nodejs';
if (type === 'bing') {
ctx.redirect(`http://cn.bing.com/search?q=${q}`);
} else {
ctx.redirect(`https://www.google.co.kr/search?q=${q}`);
}
};
// curl http://localhost:7001/search?type=bing&q=node.js
// curl http://localhost:7001/search?q=node.js
egg-router-plus
egg-router-plus 按命名空间划分路由
自己的业务域下进行管理
https://github.com/eggjs/egg-router-plus
yarn add egg-router-plus
config/plugin.js
exports.routerPlus = {
enable: true,
package: 'egg-router-plus',
};
自动注册路由
读取 controller 下的文件和 router 下的文件,进行注册路由
const Router = router.namespace('/api/v1');
const Controller = controller;
const RouterBasePath = path.resolve(__dirname, './routes/v1');
const requireRouters = async (basePath, router, controller, middleware) => {
const files = await fsPromises.readdir(basePath);
files.forEach(file => {
require(path.join(basePath, file))(router, controller, middleware);
});
};
requireRouters(RouterBasePath, Router, Controller, middleware);