【问题标题】:How to check or validate if URL exists - CORS error returned?如何检查或验证 URL 是否存在 - 返回 CORS 错误?
【发布时间】:2020-03-25 18:07:14
【问题描述】:

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

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

在“https://www.google.co.uk/”访问 XMLHttpRequest(重定向 from 'http://www.google.co.uk/') from origin '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】:

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

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

    它似乎完成了我需要它做的事情......检查互联网上是否存在 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");
          }
     });
    

    【讨论】:

      猜你喜欢
      • 2010-11-25
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2011-08-24
      • 2011-04-05
      • 2012-05-16
      • 1970-01-01
      • 2020-07-05
      相关资源
      最近更新 更多