一、中间键的使用
1、在app目录下新建middleware文件夹
2、在middleware文件夹下新建中间键文件
例如 新建一个文章浏览计数的中间键middleware/counter.js
module.exports = options =>{
return async (ctx,next)=>{
if(ctx.session.counter){
ctx.session.counter++;
}else{
ctx.session.counter = 1;
}
await next();
}
}
3、配置使用
1、全局配置使用
在config/config.default.js里面配置
config.middleware = [ ‘counter' ];
使用,在任意一个请求返回里调用const counter = ctx.session.counter;就能获取到,
然后每次刷新页面数据都会变化
2、局部使用
如果不想访问每个请求都进行计数,那么config/config.default.js里就不用进行配置
需要在路由文件app/router.js里进行配置,配置如下:
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const counter = app.middleware.counter();
const { router, controller } = app;
router.get('/', controller.home.index);
router.get("/new",counter, controller.new.index);
router.get('/new/content', controller.new.content);
router.get('/new/detail/:id', controller.new.detail);
router.get('/new/list', controller.new.newlist);
router.get('/new/girl', controller.new.getGrils);
router.get('/admin', controller.admin.index);
router.post('/test', controller.test.index);
router.post("/test/add", controller.test.add);
router.post("/test/del", controller.test.del);
router.post("/test/edit", controller.test.edit);
router.post("/test/look", controller.test.look);
router.get('/test/detail/:name/:age', controller.test.detail);
router.post("/list", controller.list.userlist);
};
使用,然后在new的请求页面里里面,没请求次,就会把计数的值counter传递过去,其他请求的页面里不会访问到这个计数插件的。
2、application扩展
1、多种对象进行扩展
Egg.js可以对内部的五种对象进行扩展,我也作了一个表格。给出了可扩展的对象、说明、this指向和使用方式。
对application对象的方法扩展
按照Egg的约定,扩展的文件夹和文件的名字必须是固定的。比如我们要对application扩展,要在/app目录下,新建一个/extend文件夹,然后在建立一个application.js文件。文件如下
/* eslint-disable strict */
module.exports = {
//方法扩展
currentTime() {
return getTime();
},
//属性扩展
get timeprop() {
return getTime();
}
};
function getTime() {
let now = new Date();
let year = now.getFullYear();
let month = now.getMonth() + 1;
let date = now.getDate();
let hour = now.getHours();
let minute = now.getMinutes();
let second = now.getSeconds();
let newTime = year + '年' + month + '月' + date + '日' + hour + ':' + minute + ':' + second;
//console.log('newtime', newTime);
return newTime;
}
写完后,不用再作过多的配置,直接在一个Controller方法里使用就可以了。比如我们要在/app/controller/new.js的index( )方法里使用。
'use strict';
const Controller = require('egg').Controller;
class NewController extends Controller {
async index() {
const { ctx, app } = this;
const list = await this.service.news.getNewList();
//const list = await ctx.model.List.findAll();
//console.log('list',list);
const username = ctx.session.username ? ctx.session.username : 'xdd.com';
const counter = ctx.session.counter;
const nowtime = app.currentTime();//--使用方法获取值
const nowtime = app.timeprop;//使用属性方法直接获取值
const msg = '后台传递到新闻页面的提示消息';
await this.ctx.render("index", {
nowtime,
msg,
list,
username,
counter,
});
}
}
module.exports = NewController;
这样,就可以在app/view/index.html模板使用
<%=nowTime%>
对application对象的属性扩展
对属性( property) 的扩展的关键字是get,也需要写在application.js文件里。
module.exports = {
//方法扩展
currentTime() {
return getTime();
},
//属性扩展
get timeprop() {
return getTime();
}
};
加入get,就会默认是一个属性,可以直接以属性的形式在controller方法里进行调用。
Egg.js中的扩展是经常使用的,所以你有必要多练习几遍。这节课我们主要学习了如何扩展application中的方法扩展和属性扩展。写扩展时要遵照Egg的约束,方法扩展和平时写的方法一样,属性扩展以get为关键字。
2、Egg.js的Extend-content的扩展
Context 指的是 Koa 的请求上下文,这是 请求级别 的对象,每次请求生成一个 Context 实例,通常我们也简写成 ctx。在所有的文档中,Context 和 ctx 都是指 Koa 的上下文对象。
访问方式
- middleware 中
this就是 ctx,例如this.cookies.get('foo')。 - controller 有两种写法,类的写法通过
this.ctx,方法的写法直接通过ctx入参。 - helper,service 中的 this 指向 helper,service 对象本身,使用
this.ctx访问 context 对象,例如this.ctx.cookies.get('foo')。
扩展方式
框架会把 app/extend/context.js 中定义的对象与 Koa Context 的 prototype 对象进行合并,在处理请求时会基于扩展后的 prototype 生成 ctx 对象。
首现在/app/extend/下新建context.js,
1、例如要获取当前的IP
/* eslint-disable strict */
module.exports = {
getIp() {
return this.request;
},
};
然后在/app/controller/home.js里面使用
/* eslint-disable quotes */
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
// console.log(this.app.foo());
console.log('请求', this.ctx.getIp());
console.log('request', this.ctx.request.foo());
const { ctx } = this;
ctx.body = "hi,主页";
}
}
module.exports = HomeController;
2、封装获取get和post请求的参数
同样在/app/extend/context.js下进行参数代码的封装
params(key) { --key 要获取的参数名
const method = this.request.method;
if (method === 'GET') {
return key ? this.query[key] : this.query;
} else {
return key ? this.request.body[key] : this.request.body;
}
}
在/app/controller/home.js里面使用
/* eslint-disable quotes */
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx, app } = this;
const prams = ctx.params('id');
console.log("prams", prams);
ctx.body = "hi,主页";
}
}
module.exports = HomeController;