Vue + Vant + Koa2 + svg-captcha 實現圖片驗證碼


繼上一篇文章,實現了登陸功能,但是缺少一個驗證碼校驗環節,今天和大家一起把圖片驗證碼功能完善起來。

 

實現功能截圖:

驗證碼校驗,若驗證碼錯誤,返回錯誤信息,驗證碼正確,提示登錄成功:

 

 

·驗證碼生成插件: svg-captcha

 

一、前端部分

前端采用 Vue + Vant 模式,驗證碼用 <van-image /> 展示出來。

 

1、引入:

import { Image as VanImage } from 'vant';

 

2、組件注冊:

components:{
  ...
  ...
  [VanImage.name]: VanImage,
},

 

3、聲明圖片 src 變量,我們取名為 imageSrc :

data() {
  return {
    ...
    ...
    imageSrc: '',
  }
}

 

4、在 <template> </template> 中添加:

<van-field
  center
  clearable
  label="驗證碼"
  placeholder="請輸入驗證碼"
>
  <template #right-icon>              <!-以插槽形式注入驗證碼 ->
    <van-image :src="imageSrc" width="80" height="40" @click="_updatePicCode" />
  </template>
</van-field>

 

 5、添加 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

 

6、設置 axios(重點),注意因為獲取驗證碼涉及跨域請求,並且后台生成的驗證碼需要存儲於 cookies 中,而 cookies 是隨着請求在前端與后端之前來回發送的,因此需要:

axios.defaults.withCredentials = true; // 表示跨域請求時是否需要使用憑證,跨域訪問需要發送cookie時一定要加

否則,點擊登錄按鈕后,后端進行驗證碼比對時,是獲取不到 cookies 中的驗證碼,也就無法比對驗證碼的正確性。

 

二、后端部分:

1、在 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;
})

 

2、驗證碼生成方法封裝在 ./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;
  }
}

 

好了,圖片驗證碼就介紹到這里,如果文章中有不正確的地方,歡迎大家留意指正。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM