img src 或者 background:url('') 中的地址是接口, 如何設(shè)置請(qǐng)求頭

問題背景:

項(xiàng)目之前傳遞token的方式,是通過cookie來傳的。(cookie中的數(shù)據(jù)默認(rèn)會(huì)跟著所有請(qǐng)求發(fā)送)因谷歌瀏覽器80版本之后,SameSite屬性默認(rèn)值改為Lax后,導(dǎo)致不同站下的cookie寫不進(jìn)去了。所以更改了傳遞token的方式,通過請(qǐng)求頭傳遞。設(shè)置了axios的請(qǐng)求頭后,其他的接口訪問都沒有問題,唯有圖片這種直接通過src或者background:url()的方式。接口就加載請(qǐng)求了,加不上請(qǐng)求頭。

解決方案

使用原生的XMLHttpRequest對(duì)象創(chuàng)建請(qǐng)求

background:url()方式

//react 代碼如下
  componentDidMount () {
     // icon為請(qǐng)求接口地址 如:http://localhost:8080/files/download?fileName=photo/a.jpg
    const { icon } = this.props  
    this.getImage(icon)
  }
  
  getImage = (icon) => {
    let request = new XMLHttpRequest();
    request.responseType = 'blob';
    request.open('get', icon, true);
    request.setRequestHeader('Authorization', '憑證信息'); 
    request.onreadystatechange = e => {
      if (request.readyState == XMLHttpRequest.DONE && request.status == 200) { 
          // this.refElement 表示的是html中的元素
           this.refElement.style.backgroundImage= `url(${URL.createObjectURL(request.response)})` ;
        }
    };
    request.send(null);
  }

   // render中的代碼
   <span ref={ref => (this.refElement = ref)} />

img src方式

  componentDidMount () { 
    const { icon } = this.props  
    this.getImage(icon)
  } 
  getImage = (icon) => {
    let request = new XMLHttpRequest();
    request.responseType = 'blob';
    request.open('get', icon, true);
    request.setRequestHeader('Authorization', '憑證信息'); 
    request.onreadystatechange = e => {
      if (request.readyState == XMLHttpRequest.DONE && request.status == 200) { 
          this.refElement.src = URL.createObjectURL(request.response);
          this.refElement.onload = () => {
                URL.revokeObjectURL(this.refElement.src);
          } 
        }
    };
    request.send(null);
  }

   // render中的代碼
   <img  ref={ref => (this.refElement = ref)} />

注:
URL.createObjectURL()
URL.revokeObjectURL()
參考:https://segmentfault.com/a/1190000020366227?utm_source=tag-newest

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。