【问题标题】:Can't check if the request succeed or not无法检查请求是否成功
【发布时间】:2020-08-26 10:08:16
【问题描述】:

我正在尝试创建一个 JavaScript 代码,允许我检查是否可以通过 URL 向给定主机发送 HTTP 请求(检查服务器是否打开)。这是我的代码:

<html>
<body>
<script>
  function checkServer(url) {
  const controller = new AbortController();
  const signal = controller.signal;
  const options = { mode: 'no-cors', signal };
  return fetch(url, options)
    .then(setTimeout(() => { controller.abort() }, 5))
    .then(response => function() 
    {
      var xhttp = new XMLHttpRequest();
      xhttp.open("GET", "http://log.mywebsite.com", true);
      xhttp.send();
    }
    )
    .catch(error => function() 
    {
      var xhttp = new XMLHttpRequest();
      xhttp.open("POST", "http://log.mywebsite.com", true);
      xhttp.send();
    }
    )
  }
  checkServer('https://blahdummydamnfck.com');
</script>
</body>
</html>

但是,虽然它不能向服务器发送 HTTP 请求,但它并没有向我的日志服务器发送日志请求。为什么会发生在我身上?

【问题讨论】:

    标签: javascript html logging xmlhttprequest


    【解决方案1】:

    fetch 不会抛出。如果请求失败,它会返回错误代码,因此 catch 不是检测丢失服务器的正确方法。改为检查response code

    来自manualfetch() 方法接受一个强制参数,即您要获取的资源的路径。它返回一个 Promise,该 Promise 解析为对该请求的响应,无论它是否成功。您还可以选择传入一个初始化选项对象作为第二个参数(请参阅请求)。

    【讨论】:

    • 那你有什么建议?
    • fetch(url, options).then(function(response) { if (response.status == "200") then { okay } else { not okay };});
    • 或responce.ok。 @EthicalHackerMinh 阅读了文档伙伴。它在大多数情况下都有帮助。
    • 它给了我这个错误:Uncaught SyntaxError: Unexpected token '{'then {
    猜你喜欢
    • 2018-01-15
    • 2021-01-28
    • 2023-02-11
    • 2011-12-29
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多