1. 程式人生 > >vue項目經驗:圖形驗證碼接口get請求處理

vue項目經驗:圖形驗證碼接口get請求處理

ray esp 需要 pre ios response image 圖片 math

  技術分享圖片

  一般圖形驗證碼處理:

直接把img標簽的src指向這個接口,然後在img上綁定點擊事件,點擊的時候更改src的地址(在原來的接口地址後面加上隨機數即可,避免緩存)

<img :src="codeImg" class="img-code" @click="updateCode" alt="驗證碼" title="點擊換一張">
export default {
  data () {
      codeImg: `${this.baseUrl}/captcha/captcha.php
  },
  methods: {
    updateCode() {
        
this.codeImg = `${this.baseUrl}/captcha/captcha.php?=${Math.random()}`; } } }

  

  但是,有一天,後端說,在接口的響應頭裏放了一些信息,需要提交form表單時,一並提交。然後用axios的get請求,尷尬了,響應的是數據流,顯示不出圖片了。

  技術分享圖片

  解決方案如下:將數據流轉換為圖片

  首先html結構不變,把js改了。

export default {
  data () {
     imgCode: ‘‘,    // 一定要有 
     captchaId: ‘‘   // 後端需要的響應頭中的信息參數
}, created () { this.updateCode() }, methods: { updateCode () { let _this = this this.axios.get(`${this.urlBase}/user/captcha?=${Math.random()}`, { responseType: ‘arraybuffer‘ }).then((res) => { // 後端需要的響應頭中的信息參數賦值 this.captchaId = res.headers[‘x-ocp-captcha-id‘]
// 轉換 let codeImg = ‘data:image/png;base64,‘ + btoa( new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ‘‘) ) _this.codeImg = codeImg }) }, } }

vue項目經驗:圖形驗證碼接口get請求處理