02-Egg-处理请求参数

241 阅读1分钟

废物不多说,直接上代码

module.exports = {
  keys: "sandy.*?",
  security: {
    csrf: {
      // 企业开发中不推荐这样做,因为是学习阶段进行本地测试,我们先这样使用,后面会说另外的方法
      ignoreJSON: true, // 默认为 false,当设置为 true 时,将会放过所有 content-type 为 `application/json` 的请求
    },
  },
};
module.exports = (app) => {
  const { router, controller } = app;
  router.get("/", controller.home.index);
  /*
  1.EggJS如何处理Get/Post请求参数?
  "和Koa一样"
  * */
  router.get("/user", controller.home.getQuery);
  router.get("/register/:name/:age", controller.home.getParams);
  router.post("/login", controller.home.getBody);
};


```home.js
const Controller = require("egg").Controller;

class HomeController extends Controller {
  async index() {
    this.ctx.body = "egg服务启动成功";
  }

  async getQuery() {
    // 获取传统get请求参数
    // this.ctx.request.query
    this.ctx.body = this.ctx.query;
  }

  async getParams() {
    // 获取动态路由形式的get请求参数
    this.ctx.body = this.ctx.params;
  }

  async getBody() {
    // 获取post请求参数
    // 如果我直接写body的话是不是和上下文冲突了,所以这里加个request
    // 默认情况下通过post传递参数是传递不了的
    // 我们通过postman工具来进行post请求
    // 因为前面说过阿里前端安全专家,负责 egg-security 等类库, 安全有保障
    // 在官方文档有提到: https://eggjs.org/zh-cn/core/security.html
    // 所以我们需要在config.default.js文件中进行配置
    this.ctx.body = this.ctx.request.body;
  }
}

module.exports = HomeController;

效果图