javascript 如何从api获取reactjs中的图像?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50344055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to GET image in reactjs from api?
提问by Ted Khi
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.
在使用 JWT 令牌进行验证后,我正在从 nodejs API 获取图像。我在浏览器中收到 GET 200 ok 响应网络标题和图片可以在预览中看到,但我不能在我的应用程序中使用它。
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.
我肯定做错了什么。请让我知道从 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>
);
}
}
回答by Pixelomo
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) )}
})
}
Then within your img
然后在你的 img 中
src={ this.state.pic }
回答by ohryan
I was able to render images from a backend call in React using a pattern similar to this using: react hooks, axios, and URL.createObjectURL
我能够使用与此类似的模式在 React 中从后端调用渲染图像:react hooks, axios, 和URL.createObjectURL
I used the URL.createObjectURL(blob)method and used the axios configuration { responseType: 'blob' }to make sure the the data type would fit.
我使用了该URL.createObjectURL(blob)方法并使用了 axios 配置{ responseType: 'blob' }来确保数据类型适合。
const ImageComponent = (imageIds) => {
const [images, setImages] = React.useState([])
React.useEffect(() => {
async function getImage (id) {
let imageBlob
try {
imageBlob = (await axiosClient.get(`/api/image/${id}`, { responseType: 'blob' })).data
} catch (err) {
return null
}
return URL.createObjectURL(imageBlob)
}
async function getImages () {
const imageArray = []
for (const id of imageIds) {
imageArray.push(await getImage(id))
}
setImages(imageArray)
}
getImages()
}, [imageIds])
return images.map((img, i) => {
return <img src={img} alt={`image-${i}`} key={i} />
})
}
[Edit]: If your api is a protected route just make sure your axios http client is initialized with the token already
[编辑]:如果您的 api 是受保护的路由,请确保您的 axios http 客户端已经使用令牌进行了初始化
回答by Aksh
var myHeaders = new Headers();
myHeaders.append("response", "image/jpeg");
myHeaders.append("psId", "");
myHeaders.append("x-api-key", "Z7dwTzHQrklCh7bvSWqhNrDTPZiLblYS");
myHeaders.append(
"Authorization",
"Bearer token"
);
var raw = "";
var requestOptions = {
method: "GET",
headers: myHeaders,
//body: raw,
redirect: "follow",
};
let response = await fetch(
"YourURL",
requestOptions
)
.then((response) => response)
.then((result) => result)
.catch((error) => console.log("error", error));
res = await response.blob();
Then in image tag in your html or jsx file you can do it as follows:
然后在您的 html 或 jsx 文件中的图像标记中,您可以按如下方式进行:
<img src={window.webkitURL.createObjectURL(res)} />

