I want to load an image from server that requires a token, but I don't know how to send the token in headers of axios or fetch request to get it loaded. How can I send headers with url to load my image from server in my React application?
Here is my image tag
<img
src={{
uri: `${activeCoverHash}`,
headers: { t: token }
}}
alt={i.name}
onLoad={() => console.log('___DONE___')}/>
but it gives me a 404 error. What can I do?
Actually I got that pattern from here, but it is only works on React Native not React.
You can load the image by fetching the image using javascript and then loading it in the src
attribute of image tag.
componentDidMount() {
axios.get(`${activeCoverHash}`, { headers: {'t': token }, responseType: 'arraybuffer'}).then((res) => {
let data = new Uint8Array(res.data);
let raw = String.fromCharCode.apply(null, data);
let base64 = btoa(raw);
let src = "data:image;base64," + base64;
this.img.src = src;
});
}
render() {
return (
<img src={""} alt={"Loading..."} ref={(e) => this.img = e} />
)
}
Using IONIC v4 and React would be:
import React from 'react';
import API from '../api';
type ImageWithAuthProps = {
url: string;
}
const ImageWithAuth: React.FC<ImageWithAuthProps> = (props) => {
// Components refs
const img: React.Ref<HTMLImageElement> = React.createRef();
// Load data
React.useEffect(() => {
API.get(`${props.url}`,
{
responseType: 'arraybuffer',
headers: {
'Accept': 'image/jpeg'
}
}).then((res) => {
const blob = new Blob([res.data], {
type: 'image/jpeg',
});
console.log("blob: ", blob);
var objectURL = URL.createObjectURL(blob);
if (img.current != null)
img.current!.src = objectURL;
});
}, []);
return (
<img src={""} alt={"Loading..."} ref={img} />
);
};
export default ImageWithAuth;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With