Web应用开发框架-egg(三)04-基础功能——路由之定义Router、restful风格的URL定义、获取路由参数

Web应用开发框架-egg(三)04-基础功能——路由之定义Router、restful风格的URL定义、获取路由参数

路由

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

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

如何定义Router
  • 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,post 等所有 HTTP 方法

  • router.get - GET
  • router.put - PUT
  • router.post - POST
  • router.patch - PATCH
  • router.delete - DELETE
restful风格的URL定义

http://www.ruanyifeng.com/blog/2018/10/restful-api-best-practices.html

如果想通过 RESTful 的方式来定义路由, 我们提供了 app.resources('routerName', 'pathMatch', controller) 快速在一个路径上生成 CRUD 路由结构。

// app/router.js
module.exports = app => {
    
    
  const {
    
     router, controller } = app;
  router.resources('/api/user', controller.posts);
};

上面代码就在 /posts 路径上部署了一组 CRUD 路径结构,对应的 Controller 为 app/controller/posts.js 接下来, 你只需要在 posts.js 里面实现对应的函数就可以了。

在这里插入图片描述

获取参数
// 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}`;
};
// 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

猜你喜欢

转载自blog.csdn.net/weixin_44867717/article/details/134130638
今日推荐