尝试检查照片链接是否使用ajax返回404。状态始终返回0

时间:2018-01-25 04:20:42

标签: javascript xmlhttprequest

我正在尝试检查照片链接是否返回404。

我正在开发localhost:xxxx,所以我猜这是一个跨学科的问题。

我最初得到No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:xxxx' is therefore not allowed access。我查看并安装了此extension,这会禁用跨源资源共享。

但是,在安装扩展程序后,我不再收到上述错误,但检查请求的status始终会生成0

我该如何解决这个问题呢?

photo = 'http://example.com/apple.jpg';

var photoCheck = new XMLHttpRequest();
photoCheck.open('HEAD', photo, true);
photoCheck.send();
console.log(photoCheck.status); // Always returns 0

2 个答案:

答案 0 :(得分:2)

您需要等待请求完成。请求正在进行时状态为0。我强烈建议使用支持promises的fetch,并且通常会使请求更容易

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

fetch('http://example.com/apple.jpg')
  .then(res => console.log(res.status))

答案 1 :(得分:2)

正如评论中所提到的,我会采取不同的方式。

如果您正在查看在线图片,则只需使用<img>元素即可。允许从任何域加载(除非您尝试将http资源引入https页)。

我尝试这样的事情......

function photoCheck(url) {
  return new Promise((resolve, reject) => {
    let img = document.createElement('img')
    img.onload = resolve
    img.onerror = reject
    img.src = url
  })
}

然后你可以轻松使用

photoCheck('http://example.com/apple.jpg').then(() => {
  console.info('Image loads ok')
}, e => {
  console.warn('Image failed to load', e)
})
相关问题