简体   繁体   English

如何在屏幕上显示 Axios 请求返回的图像?

[英]How do I display on screen an image returned by an Axios request?

I'm trying to build a component that receives from an axios authenticated route an image, an then display it on screen, but I don't know how to handle the axios response in order to make it work.我正在尝试构建一个从 axios 验证路由图像接收的组件,然后将其显示在屏幕上,但我不知道如何处理 axios 响应以使其工作。

the code so far:到目前为止的代码:

    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>
    );
}

While i was searching for an answer i found this code, but i don't know exactly how to use it:当我在寻找答案时,我发现了这段代码,但我不知道如何使用它:

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

Try this code:试试这个代码:

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>
)

Suppose that imgData is in the json from the response假设 imgData 在响应中的 json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM