需求场景
图片需要使用接口动态获取,请求接口时必须携带特定请求头
例:
接口地址为:http://img.cn/jpg/1
指定请求头:X-Requested-With=OpenAPIRequest
如果简单使用
<img src='http://img.cn/jpg/1'>
,没携带特定请求头,请求失败
解决方案
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function () {
var blob
if(xhr.readyState === 4){
// 使用URL.createObjectURL将Blob对象转换为可访问的url地址
var src = URL.createObjectURL(xhr.response)
document.getElementById('img').src = src
}
}
xhr.open('GET','http://img.cn/jpg/1', true)
// 设置响应数据格式为Blob对象
xhr.responseType = 'blob'
// 设置请求头
xhr.setRequestHeader('X-Requested-With', 'OpenAPIRequest')
xhr.send()