在使用 JWT 令牌验证后,我正在从 nodejs API 获取图像。我在浏览器中收到 GET 200 ok 响应网络标头和图片可以在预览中看到,但我无法在我的应用程序中使用它。
我肯定做错了什么。请让我知道从 API 显示图像的正确方法。在我的后端 nodejs 上,我使用 res.sendFile 发送文件。
class Card extends Component {
constructor({props, pic, token}) {
super(props, pic, token);
this.state = {
pic: pic,
};
urlFetch(data) {
fetch(data, {
headers: new Headers({
'authorization': `Bearer ${this.props.token}`,
'Content-Type': 'application/json'
})
})
.then(response => {
if (response.statusText === 'OK') {
return data // OR return response.url
}
})
}
render() {
const { pic } = this.state;
return (
<div>
<img style={{width: 175, height: 175}} className='tc br3' alt='none' src={ this.urlFetch(pic) } />
</div>
);
}
}
原文由 JKhan 发布,翻译遵循 CC BY-SA 4.0 许可协议
我能够使用类似于此的模式从 React 中的后端调用渲染图像:
react hooks
,axios
和URL.createObjectURL
我使用了
URL.createObjectURL(blob)
方法并使用了 axios 配置{ responseType: 'blob' }
以确保数据类型适合。[编辑]:如果您的 api 是受保护的路由,只需确保您的 axios http 客户端已使用令牌初始化