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

一、路由进阶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; 复制代码https://www.cnblogs.com/kbnet/p/10114932.html
50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信