XMLHttpRequest仅适用于本地主机

时间:2016-12-22 09:15:47

标签: javascript xmlhttprequest connection

我正在尝试检查js中的互联网连接:

function doesConnectionExist() {
  var xhr = new XMLHttpRequest();
  var file = "https://www.google.com";
  var randomNum = Math.round(Math.random() * 10000);

  xhr.open('HEAD', file + "?rand=" + randomNum, true);
  xhr.send();

  xhr.addEventListener("readystatechange", processRequest, false);

  function processRequest(e) {

    if (xhr.readyState == 4) {
      if (xhr.status >= 200 && xhr.status < 304) {                   
        alert("connection ok");
      } else {
        alert("connection doesn't exist!");
      }
    }
  }
}

它不起作用,显示:

  

连接不存在!

如果我通过&#34; localhost / myApp&#34;而不是&#34; www.google.com&#34;,它工作正常, 但如果我通过我的IP而不是&#34; localhost&#34;,它就不会再次工作了。

1 个答案:

答案 0 :(得分:0)

如果您的要求很简单,您可以使用启用了CORS的代理服务器。您甚至可以使用类似服务的自己设置的代理服务器。如果您只是检查单个服务器的正常运行时间,那么最好在服务器中为此服务启用CORS。

function doesConnectionExist(url) {
  var xhr = new XMLHttpRequest();
  var file = "http://cors-anywhere.herokuapp.com/" + url;
  var randomNum = Math.round(Math.random() * 10000);

  xhr.open('HEAD', file + "?rand=" + randomNum, true);
  xhr.send();

  xhr.addEventListener("readystatechange", processRequest, false);

  function processRequest(e) {
    if (xhr.readyState == 4) {
      console.log(url, xhr.status);
      if (xhr.status >= 200 && xhr.status < 304) {

        console.log("connection ok");
      } else {
        console.log("connection doesn't exist!");
      }
    }
  }
}
doesConnectionExist("http://www.marotikkaya.in");
doesConnectionExist("http://www.google.com");

相关问题