我想从需要令牌的服务器加载图像,但是我不知道如何在axios的标头中发送令牌或获取请求以使其加载。如何发送带有url的标头以从我的React应用程序中的服务器加载我的图像?
这是我的图片标签
<img
src={{
uri: `${activeCoverHash}`,
headers: { t: token }
}}
alt={i.name}
onLoad={() => console.log('___DONE___')}/>
但是它给我一个404错误。我该怎么办?
实际上我是从here那里得到的,但是它只适用于React Native而不是React。
答案 0 :(得分:1)
您可以通过以下方式加载图像:使用javascript提取图像,然后将其加载到图像标签的countrysearch
属性中。
src
答案 1 :(得分:1)
使用IONIC v4和React将是:
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;