如何在反应中显示需要不记名令牌才能访问它的图像

kir*_*oty 2 html xmlhttprequest fetch reactjs react-native

我正在尝试找到一种在我的 React 应用程序中显示图像的方法。我需要的图像需要一个不记名令牌,换句话说,当我访问此图像时,我需要传递一个带有不记名令牌的标头。我正在从 react-native 转向 react,所以在 react-native 中,我可以直接在 Image 组件中给出标题,但似乎我无法在 img 标记中传递标题,即 html 标记。所以我的问题是如何显示需要不记名令牌才能在反应中访问它的图像。

Sam*_*ala 6

使用图像基础源

constructor(props) {
   super(props);
   this.state = {
      imgSrc: '',
   };
}
Run Code Online (Sandbox Code Playgroud)
componentDidMount() {
    fetch('http://localhost:8181/images/appliance-OTHER.svg', {
         method: "GET",
         headers: { Authorization: 'Bearer eyJhbGciOiJIU' }
    }).then((response) => {
        const data = `data:${response.headers['content-type']};base64,${new Buffer(response.data).toString('base64')}`;
            this.setState({ imgSrc: data });
    });
}
Run Code Online (Sandbox Code Playgroud)
render() {
  const { imgSrc } = this.state;
  return (
     <img src={imgSrc} alt="love is gone" />
  )
}
Run Code Online (Sandbox Code Playgroud)


And*_*scu 5

如果您使用 axios,请不要忘记添加“responseType”,否则它不起作用。

axios
  .get(endpoint, {
    headers: { Authorization: 'xxxxxxxxxxxx' },
    responseType: "arraybuffer",
  })
  .then((response: any) => {
    let data = `data:${
      response.headers["content-type"]
    };base64,${new Buffer(response.data, "binary").toString("base64")}`;
Run Code Online (Sandbox Code Playgroud)