Egg虽然给我们提供了很多内置的方法,但有时候还是感觉不够用,这时候就需要我们自己对Egg中的方法进行扩展和编写。
一、对application对象的方法扩展(this.app)
简单以做一个全局的获取时间为例。比如用app.nowTime()这个全局的方法和app.Time这个全局属性,就可以获得当前时间,并显示在页面上。
注:按照Egg的约定,扩展的文件夹和文件的名字必须是固定的。比如我们要对application扩展,要在/app目录下,新建一个/extend文件夹,然后在建立一个application.js文件。
application.js文件中编写扩展
'use strict';
module.exports = {
// 方法扩展
nowTime() {
return new Date();// 简单获取,未格式处理
},
// 属性扩展
get Time() {
return new Date();
},
};
扩展写好后,不用再作过多的配置,直接在一个Controller方法里使用就可以了,home.js中添加times。
async times() {
const { ctx, app } = this;
ctx.body = app.nowTime(); //方法扩展
}
async times() {
const { ctx, app } = this;
ctx.body = app.Time; //属性扩展
}
配置路由
router.get('/times', controller.home.times);
访问127.0.0.1:7001/times
二、对context对象的方法扩展(this.ctx)
编写一个方法就是让这Get和Post请求获取参数的方法统一化,都用params( )方法。
在/app/extend文件夹下,新建一个文件context.js(此文件名称是Egg.js要求的固定写法,不能改变)
'use strict';
module.exports = {
params(key) {
const method = this.request.method;
if (method === 'GET') {
return key ? this.query[key] : this.query;
}
return key ? this.request.body[key] : this.request.body;
},
};
home.js中添加paramsTest
async paramsTest() {
const { ctx } = this;
ctx.body = ctx.params();
//ctx.body = ctx.params('name');//获取指定参数名参数
}
路由配置
router.get('/paramsTest', controller.home.paramsTest);
// router.post('/paramsTest', controller.home.paramsTest);
ctx.params()接收post和get请求的参数都可以
三、对request对象的方法扩展(this.ctx.request)
编写一个方法,以用来获取请求头中的token属性为例
Egg.js 对 Request 的扩展也需要在/app/extend文件夹下,新建一个request.js文件,然后在这个文件里写扩展属性。
'use strict';
module.exports = {
get token() {
console.log(this.get('token'));
return this.get('token');
},
};
/app/controller/home.js中添加一个getToken方法
async getToken() {
const { ctx } = this;
const gettoken = ctx.request.token;
ctx.body = {
status: 200,
data: ctx.params(),
token: gettoken,
};
}
配置路由
router.post('/gettoken', controller.home.getToken);
四、对response对象的方法扩展(this.ctx.response)
编写一个方法,以用来设置请求头中的token属性为例
在/app/extend文件夹下,新建立一个response.js文件。
'use strict';
module.exports = {
set token(token) {
this.set('token', token);
},
};
/app/controller/home.js中添加一个setToken方法
async setToken() {
const { ctx } = this;
ctx.response.token = '147852369';
ctx.body = 'setToken';
}
配置路由
router.get('/settoken', controller.home.setToken);
五、对helper对象的方法扩展(this.ctx.helper)
以把字符串进行base64加密为例
在/app/extend/文件夹下,新建一个helper.js文件。
'use strict';
module.exports = {
base64Encode(str = '') {
return new Buffer(str).toString('base64');
},
};
/app/controller/home.js中添加一个bese64方法
async bese64() {
const { ctx } = this;
const testBase64 = ctx.helper.base64Encode('hahahahahha');
ctx.body = testBase64;
}
配置路由
router.get('/bese64', controller.home.bese64);
学习日期:2021/12/24
视频参考:www.bilibili.com/video/BV1s3…
仅供个人学习和记录