一、egg安全机制配置
在config/config.defalut.js里面设置
// CSRF防跨域关闭
config.security = {
csrf: {
enable: false,
},
};
二、使用REST Client进行请求测试
在项目任意目录新建test.http文件,文件内容为
POST http://127.0.0.1:7001/test
Content-type: application/json
Authorization: token xxx
{
"name": "sample",
"time": "Wed, 21 Oct 2015 18:27:50 GMT"
}
name=lisi
在/controller/test.js如何获取上面的发送请求参数
const Controller = require('egg').Controller;
class TestController extends Controller {
async index() {
const ctx = this.ctx;
ctx.body = {
status: 200,
data: ctx.request.body--获取到传的值
};
}
}
module.exports = TestController;
注意
如果请求头是application/x-www-form-urlencoded 请求参数是name=lisi
那么ctx.request.body
返回的就是
"name": "'lisi'"
如果请求参数是
{
"name": "sample",
"time": "Wed, 21 Oct 2015 18:27:50 GMT"
}
那么返回的就是
"{\r\n "name": "sample",\r\n "time": "Wed, 21 Oct 2015 18:27:50 GMT"\r\n}": ""
但是一般我们传参都是json形式的传参,所以服务器请求头是Content-type: application/json; charset=utf-8
那么返回的就是
{
"name": "sample",
"time": "Wed, 21 Oct 2015 18:27:50 GMT"
}
三、Service服务的编写
官方对Service服务的说明
Service就是在复杂业务场景下用于做业务逻辑封装的一个抽象层。
简单来说,就是把业务逻辑代码进一步细化和分类,所以和数据库交互的代码都放到Service中。这样作有三个明显的好处。
- 保持Controller中的逻辑更加简介。
- 保持业务逻辑的独立性,抽象出来的Service可以被多个Controller调用。
- 将逻辑和展现分离,更容易编写测试用例。
个人建议只要是和数据库的交互操作,都写在Service里,用了Egg框架,就要遵守它的约定。