繁体   English   中英

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

[英]How to check or validate if URL exists - CORS error returned?

我正在尝试通过 JavaScript 检查/验证 URL 是否存在。 我找到了一些应该可以工作的代码。

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

CORS 政策已阻止从源“null”访问“ https://www.google.co.uk/ ”(从“ http://www.google.co.uk/ ”重定向)的 XMLHttpRequest:否请求的资源上存在 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);

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

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

似乎它完成了我需要它做的事情....检查互联网上是否存在 URL:

 const url = "https://www.google.com/"; 
 $.ajax({
      url: url,
      dataType: 'jsonp', 
      statusCode: {
        200: function() {
          console.log( "status code 200 returned" );
        },
        404: function() {
          console.log( "status code 404 returned" );
        }
      },
      error:function(){
          console.log("Error");
      }
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM