首页 > 解决方案 > 如何在屏幕上显示 Axios 请求返回的图像?

问题描述

我正在尝试构建一个组件,该组件从经过 axios 身份验证的路由接收图像,然后将其显示在屏幕上,但我不知道如何处理 axios 响应以使其工作。

到目前为止的代码:

    import React, {useEffect} from 'react';
import axios from 'axios'

export default function TesteImagens() {

const[img, setImg] = React.useState('')

useEffect(async ()=>{
    const token = JSON.parse(localStorage.getItem('Token'))
    const config = {
      headers: { Authorization: `Bearer ${token}` }
    };
    console.log(config)
    const imgData = await axios.get('http://127.0.0.1:3333/imagem/1610978351872-download.jpg-undefined.jpeg', config)
    console.log(imgData)
    setImg(imgData)
}, [])    

    return (
        <div>
            
        
           
        </div>
    );
}

当我在寻找答案时,我发现了这段代码,但我不知道如何使用它:

function getBase64(url) {
  return axios
    .get(url, {
      responseType: 'arraybuffer'
    })
    .then(response => Buffer.from(response.data, 'binary').toString('base64'))
}

标签: javascriptreactjsimageaxios

解决方案


试试这个代码:

useEffect(() => {
    const token = JSON.parse(localStorage.getItem('Token'))
    const config = {
      headers: { Authorization: `Bearer ${token}` }
    };
    axios.get('http://127.0.0.1:3333/imagem/1610978351872-download.jpg-undefined.jpeg', config).then(response => {
        setImg(response.imgData)
    })
}, []) 

return (
  <div>
    <img src={img} />
  </div>
)

假设 imgData 在响应的 json 中


推荐阅读