vue项目经验:图形验证码接口get请求处理

  

  一般图形验证码处理:

      直接把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
      })
    },    
  }  
}    
原文地址:https://www.cnblogs.com/EnSnail/p/8444391.html