eggjs中写restful风格的接口,并发送请求

本文介绍了一个使用 Egg.js 框架构建 RESTful API 的示例,详细展示了路由配置、控制器方法以及如何通过 Postman 进行测试。通过 `router.resources` 创建了多个资源路由,覆盖了增删查改操作,并在 `res.js` 中定义了对应的控制器方法。配置文件 `config.default.js` 中禁用了 CSRF 安全检查,以允许 Postman 测试。
摘要由CSDN通过智能技术生成
//目录局部结构
egg
|--app
|	|--controller
|	|	|--v1
|	|	|	|--res.js
|	|--router.js
|--config
|	|--config.default.js
// router.js
'use strict';
module.exports = app => {
  const { router, controller } = app;
  router.resources('restful', '/api/v1/restful', controller.v1.res);
  router.resources('restful', '/api/v1/restful/new', controller.v1.res);
  router.resources('restful', '/api/v1/restful/:id', controller.v1.res);
  router.resources('restful', '/api/v1/restful/:id/edit', controller.v1.res);
}
// res.js
'use strict';

const Controller = require('egg').Controller;
// 注意方法名字是官方规定的
class V1Controller extends Controller {
	// http://127.0.0.1:7001/api/v1/restful get
	async index() {
		const { ctx } = this;
		ctx.body = '这里是restful-index';
	}
	// http://127.0.0.1:7001/api/v1/restful/new get
	async ['new']() { //new是关键字,如果直接new(){}可能有问题
		const { ctx } = this;
		ctx.body = '这里是restful-new';
	}
	// http://127.0.0.1:7001/api/v1/restful/11  get
	async show() {
		const { ctx } = this;
		ctx.body = '这里是restful-show';
	}
	// http://127.0.0.1:7001/api/v1/restful/11/edit get
	async edit() {
		const { ctx } = this;
		ctx.body = '这里是restful-edit';
	}
	// http://127.0.0.1:7001/api/v1/restful 传入参数  post
	// https://eggjs.org/zh-cn/basics/router.html#表单内容的获取
	async create() {
		const { ctx } = this;
		ctx.body = '这里是restful-create';
		console.log(ctx.req);
	}
	// http://127.0.0.1:7001/api/v1/restful/1 put
	async update() {
		const { ctx } = this;
		ctx.body = '这里是restful-update';
	}
	// http://127.0.0.1:7001/api/v1/restful/1 delete
	async destroy() {
		const { ctx } = this;
		ctx.body = '这里是restful-destroy';
	}
}

module.exports = V1Controller;

以下是postman测试结果

get方法

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

post方法

注意:直接进行不会得到结果,需要进行一些配置
链接: 相关配置.

// config.default.js
'use strict';

module.exports = appInfo => {
  //其余内容省略
  // 这里写入
  config.security = {
	  csrf: false
  };
  
  return {
    ...config,
    ...userConfig,
  };
};

在这里插入图片描述

put方法

在这里插入图片描述

delete方法

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值