继上一篇文章,实现了登录功能,可是缺乏一个验证码校验环节,今天和你们一块儿把图片验证码功能完善起来。html
实现功能截图:前端
验证码校验,若验证码错误,返回错误信息,验证码正确,提示登陆成功:ios
·验证码生成插件: svg-captchaaxios
1、前端部分后端
前端采用Vue + Vant模式,验证码用<van-image />展现出来。跨域
一、引入:cookie
import { Image as VanImage } from 'vant';
二、组件注册:session
components:{
...
...
[VanImage.name]: VanImage,
},
三、声明图片src变量,咱们取名为imageSrc:dom
data() { return { ... ... imageSrc: '', } }
四、在<template></template>中添加:async
<van-field center clearable label="验证码" placeholder="请输入验证码" > <template #right-icon> <!-以插槽形式注入验证码 -> <van-image :src="imageSrc" width="80" height="40" @click="_updatePicCode" /> </template> </van-field>
五、添加created()方法以及点击更新验证码方法:
created() { this.$nextTick(() => this._updatePicCode()) }
methods: { _updatePicCode() { this.imageSrc = 'http://localhost:3000/users/sendPicCode?d=' + Math.random(); }, }
created()中,this.$nextTick()的用法,请参考:https://www.cnblogs.com/tugenhua0707/p/11756584.html#top
六、设置axios(重点),注意由于获取验证码涉及跨域请求,而且后台生成的验证码须要存储于cookies中,而cookies是随着请求在前端与后端以前来回发送的,所以须要:
axios.defaults.withCredentials = true; // 表示跨域请求时是否须要使用凭证,跨域访问须要发送cookie时必定要加
不然,点击登陆按钮后,后端进行验证码比对时,是获取不到cookies中的验证码,也就没法比对验证码的正确性。
2、后端部分:
一、在routes/users.js中添加响应路由:
/** * 发送SVG图片验证码 */ router.get('/sendPicCode', async function(ctx) { const picCode = tools.getCaptcha(); // 将验证码保存入 session 中,与点击登陆按钮以后,同用户输入的验证码进行比对 ctx.session.picCode = picCode.text; // 指定返回的类型 ctx.response.type = 'image/svg+xml'; ctx.body = picCode.data; })
二、验证码生成方法封装在./utils/tools.js:
const SvgCaptcha = require('svg-captcha'); /** * 工具封装 */ class Tools { //返回SVG图片验证码 getCaptcha() { const captcha = SvgCaptcha.create({ size: 4, ignoreCharsL: 'o01i', noise: 1, color: true, background: '#cc9966' }); return captcha; } }
好了,图片验证码就介绍到这里,若是文章中有不正确的地方,欢迎你们留意指正。