node_egg验证码svg-captcha插件

egg验证码svg-captcha插件

安装

$ npm install svg-captcha --save

egg中使用

// 大致的流程就是:
定义router路由=>定义一个处理该路由的Controller=>Controller把生成验证码交给Service来做=>Service调用svg-captcha生成一张svg二维码返回给controller

router部分

module.exports = app => {
const { router, controller } = app;
router.post('/verify', controller.login.verify);
}

Controller部分

const Controller = require('egg').Controller;
class LoginController extends Controller {
async verify() {
const { ctx } = this;
// 服务里面的方法
let captcha = await this.service.verifyTools.captcha();
// 返回的类型
ctx.response.type = 'image/svg+xml';
// {data: '<svg.../svg>', text: 'abcd'}
ctx.body = captcha.data;
}
}
module.exports = LoginController;

Service部分

'use strict';
const Service = require('egg').Service;
const svgCaptcha = require('svg-captcha');
// 验证码配置信息
const options = {
size: 5, // 验证码长度(显示几个字符)
fontSize: 100, // 验证码的字体大小
width: 500, // 验证码的宽度
height: 200, // 验证码的高度
background: '#cc9966', // 验证码的背景颜色
};
class VerifyToolsService extends Service {
async captcha() {
// 第三方插件,实现验证码功能
const captcha = svgCaptcha.create(options);
// 将验证码text文本保存到全局session中, 观察者/发布者订阅模式
this.ctx.session.code = captcha.text;
return captcha;
}
}
module.exports = VerifyToolsService;

posted @ 2020-03-29 16:38  前端之旅  阅读(1167)  评论(0)    收藏  举报