Egg.js路由请求get,post,put,delete

在home.js中增加一个方法huangbaokang

'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    ctx.body = 'hi, egg';
  }
  
  // 新增方法
  async huangbaokang(){
    const { ctx } = this;
    ctx.body = "hello huangbaokang"; 
  }
}

module.exports = HomeController;

在router.js中增加一个路由

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller } = app;
  router.get('/', controller.home.index);
  router.get("/huangbaokang",controller.home.huangbaokang);
};

在这里插入图片描述

如上是一个get请求
在项目中,还是需要一定的规范,分层管理代码,接下来我们新建一个控制器,模拟一个学生管理模块
在controller下新建student.js文件

const Controller = require("egg").Controller;
class StudentController extends Controller{
    async index(){
        const { ctx } = this;
        ctx.body = 'student index';
    }
}


module.exports = StudentController;

在router.js中配置

// 新增student的路由
router.get('/student',controller.student.index);

在这里插入图片描述

GET方式的两种传参方式

第一种方式,使用?加键值对的方式,使用ctx.query
在student.js中增加getStudentInfo方法

// get传参方式一:获取学生信息,模拟传参name=huangbaokang&id=100
    async getStudentInfo(){
        const { ctx } = this;
        ctx.body = ctx.query;
    }

并在router.js中增加如下路由

 router.get("/getStudentInfo",controller.student.getStudentInfo);

浏览器访问,可以看到返回前端一个json串
在这里插入图片描述
方式二,restful方式,使用ctx.params
在router.js中加入路由

  router.get("/getStudentInfo2/:name/:id",controller.student.getStudentInfo2);

在student.js中加入getStudentInfo2方法

// 方式二,使用占位符的方式模拟restful风格传参/huangbaokang/100
    async getStudentInfo2(){
        const { ctx  } = this;
        console.log(ctx.params);
        ctx.body = ctx.params;
    }

返回给前端浏览器为json串
在这里插入图片描述

Post等其他请求

在router.js中配置路由

 router.post("/createStudent",controller.student.create);

增加create方法

// post请求,模拟增加学生
    async create(){
        const { ctx } = this;
        ctx.body=ctx.request.body;
    }

使用postman模拟post请求
访问会报csrf问题
在这里插入图片描述
根据提供的链接,由于是学习,设置下关闭csrf即可
在config.default.js中加入如下配置

config.security = {
    csrf: {
      enable: false,
    },
  };

再次访问正常
在这里插入图片描述

put请求,使用ctx.params
模拟更新具体学生信息
在student.js中增加update方法

// put请求,模拟更新学生
    async update(){
        const { ctx } = this;
        ctx.body = ctx.params;
    }

在router.js中增加路由

router.put("/updateStudent/:id",controller.student.update);

使用postman模拟put请求如下:
put请求,地址为:http://localhost:7001/updateStudent/100

在这里插入图片描述
同理,delete请求
在student.js中增加delete方法

 // delete请求,模拟删除学生
    async delete(){
        const { ctx } = this;
        ctx.body = ctx.params;
    }

并在router.js中增加路由

router.delete("/deleteStudent/:id",controller.student.delete);

使用postman模拟请求
在这里插入图片描述

发布了1184 篇原创文章 · 获赞 272 · 访问量 203万+

猜你喜欢

转载自blog.csdn.net/huangbaokang/article/details/104168186
今日推荐