繼上一篇文章,實現了登錄功能,可是缺乏一個驗證碼校驗環節,今天和你們一塊兒把圖片驗證碼功能完善起來。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; } }
好了,圖片驗證碼就介紹到這裏,若是文章中有不正確的地方,歡迎你們留意指正。