GET
路由配置
router
router.get('/user/detail', controller.user.detail);
静态传参
user.js
async detail() {const { ctx } = this;ctx.body = ctx.query.id;}
动态传参
router
router.get('/user/detail2/:id', controller.user.detail2);
注意这个正则
async detail2() {const { ctx } = this;ctx.body = ctx.params.id;}
测试编写
test
it('user detail', async () => {await app.httpRequest().get('/user/detail?id=123').expect(200).expect('123');});it('user detail2', async () => {await app.httpRequest().get('/user/detail2/100').expect(200).expect('100');});
POST
路由配置
router
router.post('/user/add', controller.user.add);
工具APIPOST
Egg 框架的安全防范
为了方便发送请求进行测试:
config
config.security = {csrf: {enable: false,},};
传参
async add() {const { ctx } = this;ctx.body = { status: 200, data: ctx.request.body };}
POST 传参校验
利用 Egg的 一个插件egg-validate
官网说明
安装 yarn add egg-validate
plugin.js
'use strict';/** @type Egg.EggPlugin */exports.validate = {enable: true,package: 'egg-validate',};
user.js
async add() {const { ctx } = this;//** 制定参数规则const rule = {name: { type: 'string' },age: { type: 'number' },};ctx.validate(rule);//**ctx.body = { status: 200, data: ctx.request.body };}
如此一来,如果参数类型不符就会在终端报错,并且返回 422 状态码
测试编写
user.test.js
it('user add post', async () => {await app.httpRequest().post('/user/add').send({name: 'zhou',age: 20,}).expect(200).expect({status: 200,data: {name: 'zhou',age: 20,},});});
PUT
路由配置
router
router.put('/user/edit', controller.user.edit);
user
async edit() {const { ctx } = this;ctx.body = ctx.request.body;}
DELETE
路由配置
router
router.del('/user/del', controller.user.del);
user
async del() {const { ctx } = this;ctx.body = ctx.request.body.id;}
