【问题标题】:How to set authorization header on background-image: url()?如何在背景图像上设置授权标头:url()?
【发布时间】:2016-12-07 09:23:34
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你可以简单地在请求头中传递令牌。
  • @PiotrSołtysiak,我不明白怎么做。我正在使用背景图片:url("/service/1234");

标签: javascript http reactjs authorization


【解决方案1】:

一种方法是通过 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>

【讨论】:

  • 我遇到的唯一问题是异步性(?)。有没有办法同步做到这一点?
  • 你想做什么?服务器请求在设计上是异步的。
  • Content-Type: image/jpeg的时候呢?
猜你喜欢
  • 2019-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多