检查获取请求时图像的状态

lar*_*_82 5 javascript reactjs

我正在尝试检查 get 生成的图像的状态。如果结果是 404,我必须显示另一个图像,图像链接始终存在,但有时图像没问题,另一个返回 404..

我究竟做错了什么?谢谢!

已经尝试过:

if(data['img_info'] == 404) // always returns false even the image link is broke.
also whit data['img_info'].naturalWidth === 0 // whit the same result..
finaly i use the catch..
Run Code Online (Sandbox Code Playgroud)

这是代码:

fetch('url')
.then(function (response) {
  return response.json();
}).then(function (data) {
  const img_info = data['img-info']

    $('#content').css({'background-image' : 'url(' + img_info + ')','background-size': 'cover'})

}).catch(function () {
    console.log('error')
    const img_default = 'http://localhost/img/img-default.png'
    $('#content').css({'background-image' : 'url(' + img_default + ')','background-size': 'cover' })

  console.log("Error");

});
Run Code Online (Sandbox Code Playgroud)

同样的情况发生在反应组件中..甚至图像被破坏了

addDefaultSrc(ev){
    ev.target.src = 'http://localhost/img/img-default.png'
}


<img onError={this.addDefaultSrc} className="img-slider img-responsive" src={this.props.program['img-info']} /> 
Run Code Online (Sandbox Code Playgroud)