当前位置: 移动技术网 > IT编程>开发语言>JavaScript > egg.js-基于koa2的node.js进阶(一)

egg.js-基于koa2的node.js进阶(一)

2018年12月13日  | 移动技术网IT编程  | 我要评论

一、路由进阶egg路由的路由重定向,路由分组

router.js修改为如下格式require引用

module.exports = app => {
const { router, controller } = app;
require('./routers/admin')(app);
require('./routers/index')(app);
require('./routers/api')(app);
};

新建 routers文件夹,分别建admin.js index.js api.js放置不同内容,写法和原来的路由文件写法一致。

路由重定向

在controller中使用

this.ctx.status = 301;

this.ctx.redirect()

 

在routers文件中使用

router.redirect('/new','/',302)

二、egg中间件指定模块引用jsonp koa中间件在egg中使用

方法1

const auth = app.middleware.auth() //在单独模块中定义
module.exports = app => {
const { router, controller } = app; 
router.get('/admin/user',auth,controller.admin.user.index);
};

在路由的第二个参数填入中间键名称

router第二个参数中引用。

中间键的通用配置

enable 是否开启

match 设置只有符合条件的使用

ignore  排除使用中间件的目录,不能和match同时使用

2.//对后台管理通用配置
config.adminauth ={
match: '/admin' //对某个路由配置表示只匹配该路由
}

3.koa-jsonp使用 https://github.com/kilianc/koa-jsonp

npm i koa-jsonp

//koa 中的应用
// jsonp = require("koa-jsonp")
// app.use(jsonp())
新建中间件jsonp.js
module.exports =require("koa-jsonp");  
config.default.js中配置
config.middleware = ['jsonp'];

koa-compress的使用

建立中间件引用

module.exports =require("koa-compress");
config.default.js中配置
config.compress = {
threshold: 1024,
enable:false,
match(ctx){
if(ctx.request.url=='/yingu' || ctx.request.url == '/news'){
return true
}
return false;
}
}

非标准写法

let koajsonp = require("koa-jsonp");
module.exports = (option,app) => {
return koajsonp(option)
}

三、控制器控制器继承的使用

新建core/base.js作为公共controller

'use strict';
const controller = require('egg').controller;
class basecontroller extends controller {
async success(redirecturl = "/") {
await this.ctx.render('public/success',{url:redirecturl});
}
async error(redirecturl) {
await this.ctx.render('public/error',{url:redirecturl || "/"});
}
}
module.exports = basecontroller;

list.js中修改引用的controller

const basecontroller = require('../core/base.js');
class listcontroller extends basecontroller {  //继承basecontroller
async index() { await this.success('/news/1') //直接this使用公共内容 } }

四、定时任务模块的使用,和实现网站监控功能

app/schedule写定时任务模块,新建watchfile.js

const subscription = require('egg').subscription;
let i=0;
class watchfile extends subscription {
// 通过 schedule 属性来设置定时任务的执行间隔等配置
static get schedule() {
return {
interval: '5m', // 1 分钟间隔
type: 'all', // 指定所有的 worker 都需要执行
disable:false  //是否开启
};
}
// subscribe 是真正定时任务执行时被运行的函数
async subscribe() {
i++
console.log(i)
}
}
module.exports = watchfile;

 

 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网