如何从API获取ReactJS中的图像? [英] How to GET image in reactjs from api?
本文介绍了如何从API获取ReactJS中的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用JWT令牌进行验证后,正在从nodejs API提取图像. 我在浏览器中得到GET 200 ok响应,在预览"中可以看到网络标题和图片,但是我无法在我的应用程序中使用它.
I am fetching an image from nodejs API after verifying with JWT token. I am getting GET 200 ok response in browser Network header and picture can be seen in Preview, but I cannot use it in my app.
我肯定做错了什么.请让我知道从API显示图像的正确方法. 在后端nodejs上,我正在使用res.sendFile发送文件.
I am surely doing something wrong. Please let me know the proper way to display image from API. On my backend nodejs, I am using res.sendFile to send the file.
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>
);
}
}
推荐答案
这是我尝试过的用于获取数据的方法:
This is my tried and tested method for fetching data:
componentDidMount(){
fetch('https://www.yoursite.com/api/etc', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => {
return response.text();
})
.then((data) => {
console.log( JSON.parse(data) )
this.setState{( pic: JSON.parse(data) )}
})
}
然后在您的img中
src={ this.state.pic }
这篇关于如何从API获取ReactJS中的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文