
一般圖形驗證碼處理:
直接把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 }) }, } }
