【问题标题】:XMLHttpRequest only working for local hostXMLHttpRequest 仅适用于本地主机
【发布时间】:2016-12-22 09:15:47
【问题描述】:

我正在尝试在 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!");
      }
    }
  }
}

它不工作,显示:

连接不存在!

如果我通过“localhost/myApp”而不是“www.google.com”,它可以正常工作, 但如果我传递我的 IP 而不是“localhost”,那么它就不能再工作了。

【问题讨论】:

标签: javascript xmlhttprequest connection


【解决方案1】:

如果您的要求很简单,您可以使用启用了 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");

【讨论】:

    猜你喜欢
    • 2018-11-16
    • 2017-02-25
    • 2023-04-05
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 2011-03-30
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多