一、路由进阶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/ .js作为公共controller
\'use strict\'; const Controller = require(\'egg\').Controller; class Controller 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 = Controller;
在list.js中修改引用的controller
const Controller = require(\'../core/ .js\'); class ListController extends Controller { //继承 Controller
async index() { await this.success(\'/news/1\') //直接this使用公共内容 } }
四、定时任务模块的使用,和实现网站监控功能
在app/schedule写定时任务模块,新建watchfile.js
const Sub ion = require(\'egg\').Sub ion; let i=0; class WatchFile extends Sub ion { // 通过 schedule 属性来设置定时任务的执行间隔等配置 static get schedule() { return { interval: \'5m\', // 1 分钟间隔 type: \'all\', // 指定所有的 worker 都需要执行 disable:false //是否开启 }; } // subscribe 是真正定时任务执行时被运行的函数 async subscribe() { i++ console.log(i) } } module.exports = WatchFile;
继续阅读与本文标签相同的文章
-
还在关注“宏颜获水”?DuerOS 5.0让你更惊讶
2026-05-19栏目: 教程
-
「云栖大会现场」揭秘“淘富成真”,阿里+富士康如何孵化硬件
2026-05-19栏目: 教程
-
重磅!Apollo 5.0来了,百度变身「老司机」!
2026-05-19栏目: 教程
-
谷歌AI模型ML-Jam激发音乐家创作,人机合作或成未来大势!
2026-05-19栏目: 教程
-
OCP-052考试题库汇总(49)-CUUG内部解答版
2026-05-19栏目: 教程
