# 路由的使用

路由是定义接口的入口文件,Router 主要用来描述请求 URL 和具体承担执行动作的 Controller 的对应关系, 框架约定了 app/router.js 文件用于统一所有路由规则。

和Spring框架的那套不同的是,Egg接口的定义不是通过注解来完成的,虽然在后面的ts中有所实现,但是目前还是更倾向通过路由来指定;

# 优势

通过统一的配置,可以避免路由规则逻辑散落在多个地方,从而出现未知的冲突,集中在一起我们可以更方便的来查看全局的路由规则。

# 路由的定义

  • app/router.js 里面定义 URL 路由规则
// app/router.js
module.exports = app => {
  const { router, controller } = app;
  router.get('/user/:id', controller.user.info);
};

  • app/controller 目录下面实现 Controller
// app/controller/user.js
class UserController extends Controller {
  async info() {
    const { ctx } = this;
    ctx.body = {
      name: `hello ${ctx.params.id}`,
    };
  }
}

很简单的两步操作,就可以完成一个相对基础的Get请求的路由定义,当用户执行/user/123,user.js文件就可以通过接口的方式,执行info()函数,返回hello 123,当然这里是动态路由传参

# 详细说明

根据不同的应用场景,可以对路由进行不同的定义,支持:


router.verb('path-match', app.controller.action);
router.verb('router-name', 'path-match', app.controller.action);
router.verb('path-match', middleware1, ..., middlewareN, app.controller.action);
router.verb('router-name', 'path-match', middleware1, ..., middlewareN, app.controller.action);

路由完整定义主要包括5个主要部分:

  • verb - 用户触发动作,支持 get,post 等所有 HTTP 方法

    • router.head - HEAD
    • router.options - OPTIONS
    • router.get - GET
    • router.put - PUT
    • router.post - POST
    • router.patch - PATCH
    • router.delete - DELETE
    • router.del - delete 是一个保留字,所以提供了一个 delete 方法的别名
    • router.redirect - 可以对 URL 进行重定向处理。
  • router-name 给路由设定一个别名,可以通过 Helper 提供的辅助函数 pathFor 和 urlFor 来生成 URL。(可选)

  • path-match - 路由 URL 路径。

  • middleware1 - 在 Router 里面可以配置多个 Middleware。(可选)

  • controller - 指定路由映射到的具体的 controller 上,controller 可以有两种写法:

    • app.controller.user.fetch - 直接指定一个具体的 controller
    • 'user.fetch' - 可以简写为字符串形式

可以从上面很明确的知道:

  • 在Route定义中,可以支持多个中间件串联处理;
  • Controller 必须定义在 app/controller 目录中
  • 一个文件里面也可以包含多个 Controller 定义,在定义路由的时候,可以通过 ${fileName}.${functionName} 的方式指定对应的 Controller。
  • Controller 支持子目录,在定义路由的时候,可以通过 ${directoryName}.${fileName}.${functionName} 的方式制定对应的 Controller。
// app/router.js
module.exports = app => {
  const { router, controller } = app;
  router.get('/home', controller.home);
  router.get('/user/:id', controller.user.page);
  router.post('/admin', isAdmin, controller.admin);
  router.post('/user', isLoginUser, hasAdminPermission, controller.user.create);
  router.post('/api/v1/comments', controller.v1.comments.create); // app/controller/v1/comments.js
};

# router的实际应用

在项目里,路由的不同定义对应着不同的参数处理、响应处理,建议结合实际情况合理使用;

# 参数获取

# query 传参

路由请求时,传递的参数放置在ctx上下文的query对象中,对于需要使用的字段,可以通过对象解构直接获取哦。

// app/router.js
module.exports = app => {
  app.router.get('/search', app.controller.search.index);
};

// app/controller/search.js
exports.index = async ctx => {
  ctx.body = `search: ${ctx.query.name}`;
};

// curl http://127.0.0.1:7001/search?name=egg

# 动态路由传参

路由传参是基于RESTful风格将需要传递的参数放置在接口路由中,以动态变化的情况进行参数传递。

// app/router.js
module.exports = app => {
  app.router.get('/user/:id/:name', app.controller.user.info);
};

// app/controller/user.js
exports.info = async ctx => {
  ctx.body = `user: ${ctx.params.id}, ${ctx.params.name}`;
};

// curl http://127.0.0.1:7001/user/123/xiaoming

# 复杂参数传递

路由里面也支持定义正则,可以更加灵活的获取参数

// app/router.js
module.exports = app => {
  app.router.get(/^\/package\/([\w-.]+\/[\w-.]+)$/, app.controller.package.detail);
};

// app/controller/package.js
exports.detail = async ctx => {
  // 如果请求 URL 被正则匹配, 可以按照捕获分组的顺序,从 ctx.params 中获取。
  // 按照下面的用户请求,`ctx.params[0]` 的 内容就是 `egg/1.0.0`
  ctx.body = `package:${ctx.params[0]}`;
};

// curl http://127.0.0.1:7001/package/egg/1.0.0

不过这种一般使用较少,代码可读性低

# body传参

body对象传参,一般是基于非GET请求的接口路由,传递的内容为前端通过表单传递的数据。


// app/router.js
module.exports = app => {
  app.router.post('/form', app.controller.form.post);
};

// app/controller/form.js
exports.post = async ctx => {
  ctx.body = `body: ${JSON.stringify(ctx.request.body)}`;
};

// 模拟发起 post 请求。
// curl -X POST http://127.0.0.1:7001/form --data '{"name":"controller"}' --header 'Content-Type:application/json'

# 重定向

重定向可以根据内部重定向和外部重定向来实现;这里的内外可以根据是否直接在路由上进行302出重定向跳转。

# 内部重定向

内部重定向很简单,就直接在路由的定义上完成302重定向跳转。

// 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


# 外部重定向

与内部重定向不同的是,外部重定向的实现逻辑需要在路由定义对应的Controller方法中通过redirect()方法来实现。

// 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框架可以快速构建后端接口,但是随着业务量的增加、功能越发复杂,接口路由势必会非常多,所以可以按照业务范围,分层进行结构划分,避免给排查问题带来困扰。

// 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);
};

这种是比较理想的分层方式,只是添加app/router目录,通过模块引入的方式,进行拆分。当然也是可以借助插件egg-router-plus (opens new window),内部实现了自动加载;

最近更新: 1/19/2021, 11:03:12 PM