https://eggjs.org/zh-cn/basics/router.html

router.js

使用路由的步骤

  1. 配置路由
  2. 编写控制器
  3. 配置文件 ```javascript ‘use strict’;

/**

  • @param {Egg.Application} app - egg application */ module.exports = app => { const { router, controller } = app; router.get(‘/‘, controller.home.index); router.get(‘/sku’, controller.sku.index); }; ```

controller

app/controller/sku.js

  1. 'use strict';
  2. const Controller = require('egg').Controller;
  3. class SkuController extends Controller {
  4. async index() {
  5. const { ctx } = this;
  6. ctx.body = 'sku实例成功';
  7. }
  8. }
  9. module.exports = SkuController;

image.png

路由参数

ctx.query

url?id=12&name=lucy

  1. class SkuController extends Controller {
  2. async index() {
  3. const { ctx } = this;
  4. ctx.body = ctx.query;
  5. }
  6. }

ctx.params

router.get(‘/sku/detail/:id’, controller.sku.detail)
url/list-detail/23

  1. class SkuController extends Controller {
  2. async index() {
  3. const { ctx } = this;
  4. ctx.body = ctx.params;
  5. }
  6. }

redirect重定向

controller/news.js

  1. async index() {
  2. this.ctx.status = 302;
  3. this.ctx.redirect('/shop')
  4. }

router.js重定向

  1. router.redirect('/list', '/index',302);