如何在background-image上设置授权标头:url()?

时间:2016-12-07 09:23:35

标签: javascript http reactjs authorization

我正在尝试通过REST API检索背景图像。

但是,要这样做,我需要授权。

令牌可以从应该加载背景图像的上下文中获得,但我不知道如何将它添加到请求中。

有什么想法吗?这有可能吗?

在另一种方法中,我使用我的网络服务器为特定上下文中的所有请求添加授权。这很好,但不再可能了。

1 个答案:

答案 0 :(得分:5)

一种方法是通过Javascript请求图像,设置正确的标题,然后将图像显示为对象URL / blob。这是一个例子:

fetch('https://i.imgur.com/PLKabDV.png', { headers: {
    "Content-Type": "application/json" // this header is just an example, put your token here
  } })
  .then(response => response.blob())
  .then(blob => {
    let img = document.getElementById('image');
    let url = URL.createObjectURL(blob);
    img.style.backgroundImage = `url(${url})`;
  })
<div id="image" style="width: 430px; height: 430px;"></div>