node_egg路由Router

路由(Router)

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

定义路由(Router)

  // app/router.js 里面定义 URL 路由规则
  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() {
      this.ctx.body = `hello ${ctx.params.id}`, 使用params接收
    }
  }
Router详细定义说明,完整路由定义包括5个主要部分
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);
1. verb: 用户触发动作,get,post等所有HTTP方法
2. router-name: 给路由取一个别名,可以通过 Helper 提供的辅助函数 pathFor 和 urlFor 来生成 URL
3. path-match: 路由URL路径
4. middleware1: 在router里面可以配置多个中间件
5. controller: 指定路由映射到具体的controller上

注意事项

1. 在router定义中,可以支持多个middleware(中间件)
2. controller必须定义在app/controller目录中
3. 一个文件中可以包含多个Controller定义,定义路由的时候可以通过${fileName}.${functionName}的方式指定对应的controller
4. Controll支持子目录,可以通过${directoryName}.${fileName}.${functionName}的方式获取
// app/router.js
module.exports = app => {
  const { router, controller } = app;
  router.get('/home', controller.home);
  router.get('/user/:id', controller.user.page); // 动态路由,可以接收参数id
  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
};

参数获取

Query String方式
// app/router.js
module.exports = app => {
  app.router.get('/search', app.controller.search.index);
};
// app/controller/search.js
exports.index = async ctx => {
  ctx.body = `searchInfo: ${ctx.query.name}`; // => 'searchInfo: egg'
};

// curl http://127.0.0.1:7001/search?name=egg
参数命名方式(动态路由)
// 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 = `userInfo: ${ctx.params.id}, ${ctx.params.name}`; // => 'userInfo: 123, xiaoming'
};

// curl http://127.0.0.1:7001/user/123/xiaoming
表单内容的获取
// 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请求
let options = {
  url: '/form',
  method: 'post',
  data: {name: 'jack', age: 18},
  headers: {'Content-Type': 'application/json'}
}
axios(options).then(data=> {console.log(data)}) 
//=> 'body: {name: 'jack', age: 18}' promise对象

// 注意,这里直接发起post请求会报错
// 原因:框架内部针对表单POST请求均会验证CSRF的值,因此我们在表单提交时,请带上CSRF key 进行提交
// 校验是因为框架中内置了安全插件egg-security,提供了一些安全的实践,默认是开启的,
// 详情查看:https://eggjs.org/zh-cn/core/security.html#安全威胁csrf的防范
// 如果需要关闭其中一些安全防范,直接设置该项的 enable 属性为 false 即可
// config/config.default.js
exports.security = {
  csrf: false
};

重定向

内部重定向
// app/router.js
module.exports = app => {
  app.router.get('/home/index', app.controller.home.index);
  app.router.redirect('/', '/home/index', 302); //根路由重定向/home/index路由
};
// 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 = this.ctx.request.query.type;
  const q = this.ctx.request.query.q || 'node.js';
  if (type === 'bing') {
    this.ctx.redirect(`http://localhost:7001/home/index?q=${q}`);
  } else {
    this.ctx.redirect(`http://localhost:7001/user/123/jack?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);
};
posted @   前端之旅  阅读(1261)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示