前端请求获取验证码接口,后端生成返回给前端,同时存入session
前端填写验证码,提交后和后端session里面存的值做对比
npm install --save svg-captcha
eggjs 使用案例
const svgCaptcha = require('svg-captcha'); // 顶部引入
captcha() {
const { ctx } = this
let captcha = svgCaptcha.createMathExpr({
mathMin: 1,
mathMax: 9,
background: '#FFF'
})
ctx.session.captcha = captcha.text
ctx.body = captcha.data
}
// 这里是生成captcha的逻辑,给前端data部分,是个svg,前端去渲染。后端session里保存text部分
// 这里是数字,换成字母也是一样的,去掉mathMin,mathMax参数即可
// 前端接口获取,渲染
<svg class="svg-icon" aria-hidden="true" v-html="svgContent"></svg>
登陆注册时,将验证码输入提交给后端
// 前端提交后,后端比对
let { username, password, captcha } = this.ctx.request.body
if (captcha && captcha === this.ctx.session.captcha) {
console.log('校验码正确,可以登录')
} else {
console.log('校验码不正确')
return
}
网友评论