javascript - 如何在屏幕上显示 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'))
}
解决方案
试试这个代码:
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 中
推荐阅读
- python - 有没有办法让 set 消耗更少的内存?
- r - geom_ribbon 分类填充像两条单独的丝带一样工作
- ruby-on-rails - 我正在尝试在 Rails 上安装 ruby,但它告诉我我还没有安装 gem byebug 11.0.1 但我已经安装了?
- c# - Swagger codegen - 更改 API 类名称的生成方式
- git - 如何通过在 Flutter 中运行集成测试来解决此问题?
- postgresql - 如何检查所选列的任何行中是否存在记录?
- python - 如何删除csv文件中烦人的数据
- arrays - 两个排序数组的第 K 个元素
- wordpress - Wordpress 页面更新未在全球发布
- python-3.x - 是否可以在不将字符串分配给变量的情况下访问字符串元素?