抓取 ERR_CONNECTION_REFUSED

catch fetch ERR_CONNECTION_REFUSED

我一定是变老了 google 搜索因为如果你使用 javascript 的 fetch 而不是旧的 XMLHttpRequest

我正在尝试测试我的虚拟机是否在线。 VM 的其余部分已锁定,但我留下了一个开放端点用于测试。

我尝试使用 status 检查服务器是否已启动,但给我的错误与响应错误不同:

fetch("https://rockosmodernserver.westus2.cloudapp.azure.com/ ", {
            method: "GET",
            }).then(response => response)
            .then(data => {
                if (data.status == 200){
                    console.log("server is up")
                }
                else{
                 console.log("server is down!!")   
                }
            })

如果服务器正常运行,但如果服务器关闭,我会得到:

VM739:1 GET https://rockosmodernserver.westus2.cloudapp.azure.com/ net::ERR_CONNECTION_REFUSED

当我尝试用谷歌搜索时,我得到了 XMLHttpRequest 的解决方案,但没有找到获取模块的解决方案。

如果服务器没有响应,fetch将其视为connection failure并在catch()块中处理。 fetch 仅在连接成功时执行 then() 块。如果连接不成功,将执行 catch() 块。

fetch('something')
 .then( response => {})
 .catch(error => {
   // handle error here
 })

Checking that fetch was successful

您正在寻找捕获块。在 catch 块中,您可以获取错误。在下面的示例中,您可以访问错误对象。

fetch("https://rockosmodernserver.westus2.cloudapp.azure.com/ ", {
    method: "GET",
    }).then(response => response)
    .then(data => {
        console.log("server is up")
    })
    .catch((error) => {
      console.error('Error:', error);
      console.log("server is down!!")   
    });

如果服务器没有应答,他就不能给你答复。 这意味着没有状态代码。

更新: 当遇到网络错误或 CORS 在 server-side 上配置错误时,fetch() promise 将拒绝并返回 TypeError,尽管这通常意味着权限问题或类似问题——例如,404 不构成网络错误。对成功的 fetch() 的准确检查包括检查承诺是否已解决,然后检查 Response.ok 属性 的值为真。代码看起来像这样:

  fetch('flowers.jpg')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not OK');
    }
    return response.blob();
  })
  .then(myBlob => {
    myImage.src = URL.createObjectURL(myBlob);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#checking_that_the_fetch_was_successful

第一次编辑: 通过使用超时并跟踪超时的发生,此解决方案可能会有所帮助。