egg.js 解决路由映射过多的两种方案

一、需求

egg.js 在配置路由的过程中如果将所有的路由全部放在 app/router.js 里面,难免显得太过于臃肿了。

而 egg 本身提供了两种方案用于解决路由映射过多的问题。

二、通过 require 解决

这种方式无非是将不同的路由在不同的文件中配置,然后在去 require,而我在 koa-generator-postbird 这个 koa2 的脚手架中也是这么规范的。

要通过 require 解决路由映射过多的问题,则创建一个新的文件夹 app/router 来存放其他的路由文件。

下面示例通过创建 app/router/home.js 和 app/router/news.js 来区分两种路由,创建路由的方式和在 router.js 中创建路由的方式一样。

1、app/router/home.js

module.exports = app => {
  const {router,controller} = app;
  router.get('/',controller.home.index);
  router.redirect('/index','/');
};

2、app/router/news.js

module.exports = app => {
  const {router,controller} = app;
  router.get('/news',controller.news.index);
  router.redirect('/news/list','/news');
}

3、合并路由

最后在 app/router.js 中引入两个文件的路由即可。

需要注意实际上是对方法的调用,传入 app 参数。 

app/router.js :

module.exports = app => {
  require('./router/home')(app);
  require('./router/news')(app);
};

4、效果:

省略了 controller 的代码。

22.jpg

11.jpg

三、使用 egg-router-plus

上面通过 require 解决路由映射过多的问题的时候,实际上只是将路由定义在不同文件中而已,形式上的分开。

而很多 PHP 框架如 Laravel 往往可以通过 namespace 区分不同的路由,在路由配置上非常好用。

使用 egg-router-plus 和 上面 require 的方式并不冲突,在单独的路由文件如 app/router/news.js 中使用插件即可。

1、安装插件

yarn add egg-router-plus

2、启用插件

config/plugin.js

exports.routerPlus = {
  enable:true,
  package:'egg-router-plus'
};

3、配置路由

以 app/router/news.js 中的路由举例,我想让所有的路由中均以 /news 作为前缀,而不需要每个路由后面写上这个前缀。

app/router/news.js

module.exports = app => {
  const {router,controller} = app;
  const newsRouter = router.namespace('/news');
  newsRouter.get('/',controller.news.index);
  router.redirect('/news/list','/news');
} 

其他代码不变,则效果和之前一样。

4、存在的问题

目前 egg-router-plus 是存在一个问题的,文档中也有说明。

尽管使用 egg-router-plus 配置了 namespace 的路由,但跳转还是建议使用 app.router 进行跳转。

可以看到我在上面的代码中,跳转的时候,使用了 router.redirect('/news/list','/news/),而不是使用 newsRouter.redirect(from,to)

存在的问题是当使用 newsRouter.redirect(from,to) 的时候,from 会遵循 namespace 的前缀,但是 to 不会遵循 namespace 的前缀。

比如官方给的示例:

const subRouter = app.router.namespace('/sub');

// will redirect `/sub/go` to `/anyway`, not `/sub/anyway`
subRouter.redirect('/go', '/anyway');

尽管使用了 subRouter.redirect(),但是最终跳转规则是从 /sub/go 跳转到 /anyway,而不是 /sub/anyway,目前这个问题尚未被解决。

猜你喜欢

转载自blog.csdn.net/u010365819/article/details/84345349
今日推荐