Eggjs 已经有了中间件、扩展机制,为什么还要插件?
- 与中间件的关系:中间件更适合处理请求,插件可以处理业务逻辑
- Eggjs 中插件相当于一个微型应用
- 插件不包括 router.js 和 controller.js 控制器
这个插件存放位置也讲究
新建一个最外层的 lib 文件夹
插件package
lib/plugin/egg-auth/app/package.json
{"name": "egg-auth","eggPlugin": {"name": "auth"}}
真正插件代码
lib/plugin/egg-auth/app/middleware/auth.js
/* eslint-disable no-unused-vars */'use strict';module.exports = options => {return async (ctx, next) => {const url = ctx.request.url;const user = ctx.session.user;if (!user) {ctx.body = {status: 403,errMsg: '用户未登录',};} else {await next();}};};
从 session 中取得 user 元素,判断用户是否登录,如果没登录就返回 403 ,登录了就正常继续
全局插件配置
plugin.js 中 package 属性主要是线上安装的一些依赖包, 如果是本地的需要用 path 属性
plugin.js
const path = require('path');exports.auth = {enable: true,path: path.join(__dirname, '../lib/plugin/egg-auth'),};
session 扩展 中中间件额外的配置
app.js
app.config.coreMiddleware.push('auth');
将该插件放入 coreMiddleware 数组中,此时如果没有登录,那么每个界面都会显示
但是有些页面是不需要登陆验证的,如主页面、用户页面、登入登出
config.default.js
config.auth = {exclude: ['/home', '/user', '/login', '/logout'],};
再回到 auth.js 修改判断条件为
if (!user &&!options.exclude.includes(ctx.request.url.split('?')[0])) {
.split('?')[0] 是考虑 get 请求的情况,以 ? 隔开并取第一个元素 所得的就是 url
info:获取本机信息插件
对插件进行配置
plugin.js
exports.info = {enable: true,path: path.join(__dirname, '../lib/plugin/egg-info'),};
lib/plugin/egg-info/app/package.json
{"name": "egg-info","eggPlugin": {"name": "info"}}
node.js 获取电脑的基本信息
lib/plugin/egg-info/app/extend/context.js
'use strict';const os = require('os');const cpus = os.cpus().length;const platform = os.type();const memory = Math.ceil(os.totalmem() / Math.pow(2, 30)) + 'G';module.exports = {get info() {return {memory,platform,cpus,url: this.request.url,};},};
