前端图片验证码 axios 获取和展示实现代码

204 阅读1分钟
axios.get('图片验证码http地址', { responseType: "arraybuffer" }).then((res) => {
    // 拼接成base64图片数据
    let pngData = "data:image/png;base64," + btoa(new Uint8Array(res).reduce((source, byte) => source + String.fromCharCode(byte), ''))
    // 下面可以随意使用该图片了
})

代码备忘。 遇到了一个代码场景,验证码的图片不是直接设置src地址,而是通过异步请求获取图片数据,然后绑定显示。