您的位置:首页 > 产品设计 > UI/UE

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

2018-02-12 13:56 1926 查看
  


  一般图形验证码处理:

直接把
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
})
},
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐