Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

javascript - 如何检查或验证URL是否存在-返回CORS错误?(How to check or validate if URL exists - CORS error returned?)

I'm trying to check/validate if a URL exists, via JavaScript.

(我正在尝试通过JavaScript检查/验证URL是否存在。)

And I've found some code which should work.

(而且我发现了一些应该起作用的代码。)

However, I've ran into the CORS error.

(但是,我遇到了CORS错误。)

Seems my request keeps getting blocked:

(似乎我的请求不断被阻止:)

Access to XMLHttpRequest at ' https://www.google.co.uk/ ' (redirected from ' http://www.google.co.uk/ ') from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

(CORS政策禁止从来源“ null”访问“ https://www.google.co.uk/ ”(从“ http://www.google.co.uk/ ”重定向)的XMLHttpRequest。 Access-Control-Allow-Origin'标头存在于请求的资源上。)

How can I resolve this with JS, with no server side code?

(如何在没有服务器端代码的情况下使用JS解决此问题?)

I want to handle this entirely on the front-end/client-side:

(我想完全在前端/客户端上处理此问题:)

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);
  ask by Reena Verma translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found a solution, which encourages the use of fetch() API , which bypasses the CORS error/block.

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

However, I wasn't sure if there are any cons/disadvantages, to use this approach?

(但是,我不确定使用此方法是否有任何缺点/缺点?)

It seems it does what I need it to do.... to check a URL is exists on the internet:

(似乎它做了我需要做的事情。...检查Internet上是否存在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");
  }

});

(});)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...