(一)项目背景
图形验证码后端接口返回一张图片,前端需要将返回的图片放到前端页面中
(二)解决方法以及代码
axios.get(API.getImgCode, {
params: params,
responseType: 'blob' // 必须说明 axios 请求类型
}).then((res) => {
this.setState({
imgCodeUrl: window.URL.createObjectURL(res.data) // 后端返回前端渲染
})
}).catch(() => {
this.setState({
imgCodeUrl: require('@/assets/imageFail.png') // 默认图片
})
})
(三)注意点汇总
1. axios 请求必须 添加 responseType, 不然图片不显示
2. 拿到接口的二进制
把这个二进制 window.URL.createObjectURL() 就ok
(四)blob 介绍