Eggjs中的路由配置
- 官網:https://eggjs.org/zh-cn/basics/router.html
路由添加多箇中間件支持
示例:
const auth1 = app.middleware.auth1();
const auth2 = app.middleware.auth2();
router.get('/', auth1, auth2, controller.home.index);
給路由起別名
router.get('index', '/', controller.home.index); // 名稱爲 index
路由重定向
1 ) 路由內部重定向
路由重定向
module.exports = app => {
app.router.get('index', '/home/index', app.controller.home.index);
app.router.redirect('/', '/home/index', 302); // 這種寫法是將 / 重定向到 /home/index,有利於seo優化
};
2 ) 路由外部重定向
控制器重定向,默認是臨時重定向302, 一般登錄成功後的重定向
// 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.status = 301; // 把重定向改爲301 永久重定向
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
路由分組(路由映射)
我們並不建議把路由規則邏輯散落在多個地方,會給排查問題帶來困擾
下面用模塊化劃分的方式來進行分組
// app/router.js
module.exports = app => {
require('./router/news')(app);
require('./router/admin')(app);
};
// 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);
};