如何检查或验证URL是否存在-返回CORS错误?

问题描述 投票:0回答:1

我正在尝试通过JavaScript检查/验证URL是否存在。而且我发现了一些应该起作用的代码。

但是,我遇到了CORS错误。似乎我的请求不断被阻止:

在“ https://www.google.co.uk/”处访问XMLHttpRequest(已重定向来自“ http://www.google.co.uk/”)(原点“ null”)已被阻止通过CORS策略:在上不存在“ Access-Control-Allow-Origin”标头所请求的资源。

我如何在没有服务器端代码的情况下使用JS解决此问题?我想完全在前端/客户端上处理此问题:

var MrChecker = new XMLHttpRequest(),
CheckThisUrl = "http://www.google.co.uk";

// Opens the file and specifies the method (get)
// Asynchronous is true
MrChecker.open('get', CheckThisUrl, true);

//check each time the ready state changes
//to see if the object is ready
MrChecker.onreadystatechange = checkReadyState;

function checkReadyState() {
    if (MrChecker.readyState === 4) {

        //check to see whether request for the file failed or succeeded
        if ((MrChecker.status == 200) || (MrChecker.status == 0)) {
          console.log(CheckThisUrl + ' page is exixts');
        }
        else {
          console.log(CheckThisUrl + ' not exists');
        return;
        }
    }
}
MrChecker.send(null);
javascript validation cors xmlhttprequest http-headers
1个回答
0
投票

我找到了一个鼓励使用fetch()API的方法,该方法绕过了CORS错误/块。

但是,我不确定使用这种方法是否有任何缺点/缺点?

似乎它做了我需要做的...。检查URL是否存在于互联网上:

fetch('http://google.com', {mode: 'no-cors'}).then(r=>{
  console.log('google is reachable');
  })
  .catch(e=>{
    console.log('google is not there');
    });

fetch('http://fakeservertahtdoesntexist.com', {mode: 'no-cors'}).then(r=>{
  console.log('fake is reachable');
  })
  .catch(e=>{
    console.log('fake is not there');
    });
© www.soinside.com 2019 - 2024. All rights reserved.