首页 > 解决方案 > React 使用 fetch 从 api 获取图像

问题描述

我需要使用 fetch api 获取图像。我的同事说对服务器的调用应该返回一个base64字符串来显示图像。图片需要经过身份验证,我不能只使用它的网址。这就是我所拥有的:

fetch(`${apiUrl}filestore/${logo.name}`, {
        
        .then(res => console.log(res)
        

我不太确定如何获取 base64 字符串。显然我没有使用正确的获取。这是控制台中显示的内容![屏幕截图][1]

标签: javascriptreactjsfetch

解决方案


尝试将 res 格式化为 json。然后检查资源。

fetch(`${apiUrl}filestore/${logo.name}`, {
  method: 'GET',
  headers: {
    Authorization: JSON.parse(localStorage.getItem('Hidden'))
      ? `Bearer ${JSON.parse(localStorage.getItem('Hidden')).access_token}`
      : '',
  },
})
.then(res => return res.json())
.then(res => console.log(res))


推荐阅读