假设我有这样的代码:
<img src='images/whatever.jpj' width='' height=''/>
Run Code Online (Sandbox Code Playgroud)
如何为此请求配置自定义标头?
将不胜感激任何帮助
rob*_*bie 33
我来晚了,但是你可以用XMLHttpRequest一个blob 做到这一点.
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob'; //so you can access the response like a normal URL
xhr.onreadystatechange = function () {
if (xhr.readyState == XMLHttpRequest.DONE && xhr.status == 200) {
var img = document.createElement('img');
img.src = URL.createObjectURL(xhr.response); //create <img> with src set to the blob
document.body.appendChild(img);
}
};
xhr.open('GET', 'http://images.example.com/my_secure_image.png', true);
xhr.setRequestHeader('SecretPassword', 'password123');
xhr.send();
Run Code Online (Sandbox Code Playgroud)
如果需要,可以检查以确保blob的MIME类型是图像.
您无法更改浏览器对<img>标记加载的资源的HTTP请求.无论你想做什么,你都需要找到另一种方法.
例如,您可以通过自己的服务器代理请求并修改那里的标头.或者,您可以使用查询字符串参数化资源的URL.
正如Alex指出的那样,您也可以使用一个XmlHTTPRequest对象加载图像数据并使用该setRequestHeader功能,但我怀疑您可以设置哪些标题(我怀疑您可以欺骗引用者或用户代理,例如,虽然我没有测试过这个).
试试(打开控制台>网络>名称:200.jpg>RequestHeaders>你好:世界!)
<img src onerror="fetch('https://picsum.photos/200',{headers: {hello:'World!'}}).then(r=>r.blob()).then(d=> this.src=window.URL.createObjectURL(d));" />Run Code Online (Sandbox Code Playgroud)
这可以使用Service Worker来完成。在您的 Service Worker 中,处理 fetch 事件,并更改请求的模式和标头:
self.addEventListener('fetch', function(event) {
const newRequest = new Request(event.request, {
headers: {"Authorization": "Bearer XXX-my-token"},
mode: "cors"
});
return fetch(newRequest);
}
Run Code Online (Sandbox Code Playgroud)
将模式从更改no-cors为很重要cors,否则标头将被默默丢弃。