Reactjs 是否有一种方法可以显示安全和性能良好的图像?
我有一个项目。一个应用程序是api项目,另一个项目是identity server。由identity server使用承载令牌保护的Api项目 Api项目在FileController中有一个函数。此函数用于返回图像url。此函数应该需要授权标头中的beraer令牌才能执行 此函数如下所示Reactjs 是否有一种方法可以显示安全和性能良好的图像?,reactjs,performance,Reactjs,Performance,我有一个项目。一个应用程序是api项目,另一个项目是identity server。由identity server使用承载令牌保护的Api项目 Api项目在FileController中有一个函数。此函数用于返回图像url。此函数应该需要授权标头中的beraer令牌才能执行 此函数如下所示 [HttpGet] [Route("api/file/{types}/{param1}")] public string Files(string types, string param1) { r
[HttpGet]
[Route("api/file/{types}/{param1}")]
public string Files(string types, string param1)
{
return _fileService.GetDefaultLogoPath((Model.Enum.LogoType)logoType);
}
我有一个react组件来显示api返回url。该组件如下所示
public componentDidMount() {
this.fetchImage();
}
fetchImage = () => {
fetch(this.props.imageUrl, {
headers: {
'Authorization': 'Bearer ' + 'AccessToken',
'Access-Control-Allow-Origin': '*'
}
}).then((response: any) => {
if (response.status === 200) {
return response.text();
} else {
throw(new Error(response.statusCode));
}
}).then(imageUrl => {
if (this.props.preventCaching) {
imageUrl += (imageUrl.indexOf('?') > 0 ? '&' : '?') + '_rnd=' + Date.now();
}
this.setState({ source: imageUrl });
})
.catch((err) => {
_logger.error('in componentDidMount -> image could not be loaded -> ' + this.props.imageUrl, err);
this.setState({ source: _common.GetDefaultImages(this.props.imgType ? '' : this.props.imgType as string) });
});
}
onClick = (evt: any) => {
if (typeof this.props.onClick === 'function') {
this.props.onClick(evt);
}
}
public render() {
return <img
style={this.props.style}
src={this.state.source}
className={this.props.class}
width={this.props.width}
height={this.props.height}
onError={typeof this.props.onError === 'function' ? this.props.onError : _common.OnErrorImageSrc }
data-imgtype={this._imgType}
onClick={this.onClick}
/>;
}
公共组件didmount(){
this.fetchImage();
}
fetchImage=()=>{
获取(this.props.imageUrl{
标题:{
“授权”:“承载人”+“访问令牌”,
“访问控制允许来源”:“*”
}
})。然后((响应:任意)=>{
如果(response.status==200){
返回response.text();
}否则{
抛出(新错误(response.statusCode));
}
})。然后(imageUrl=>{
if(this.props.preventCaching){
imageUrl+=(imageUrl.indexOf(“?”)>0?“&”:“?”)+“\u rnd=”+Date.now();
}
this.setState({source:imageUrl});
})
.catch((错误)=>{
_logger.error('in componentDidMount->image无法加载->'+this.props.imageUrl,err);
this.setState({source:_common.GetDefaultImages(this.props.imgType?'':this.props.imgType as string)});
});
}
onClick=(evt:any)=>{
if(typeof this.props.onClick==='function'){
this.props.onClick(evt);
}
}
公共渲染(){
返回;
}
此组件为api url添加承载令牌。这段代码是正确的,但是更多的api调用会在页面中显示更多的图像。例如,100图像
有没有一种方法可以显示安全且运行良好的图像?使用cookies存储您的令牌,这样您就不必担心每次都将其添加为标头。我将令牌保存到本地存储,但必须在每个请求中添加承载令牌。它没有执行@JMadelaineDon操作,无法将令牌保存到本地存储,这是不安全的。非常感谢。我会小心的。