Javascript:检查服务器是否在线?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5224197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:14:17  来源:igfitidea点击:

Javascript: Check if server is online?

javascript

提问by Skizit

What's the fastest way to check if my server is online via JavaScript?

通过 JavaScript 检查我的服务器是否在线的最快方法是什么?

I've tried the following AJAX:

我尝试了以下 AJAX:

function isonline() {
    var uri = 'MYURL'
    var xhr = new XMLHttpRequest();
    xhr.open("GET",uri,false);
    xhr.send(null);
    if(xhr.status == 200) {
        //is online
        return xhr.responseText;
    }
    else {
        //is offline
        return null;
    }   
}

The problem is, it never returns if the server is offline. How can I set a timeout so that if it isn't returning after a certain amount of time, I can assume it is offline?

问题是,如果服务器离线,它永远不会返回。如何设置超时,以便如果它在一段时间后没有返回,我可以假设它处于离线状态?

回答by gilly3

XMLHttpRequestdoes not work cross-domain. Instead, I'd load a tiny <img>that you expect to come back quickly and watch the onloadevent:

XMLHttpRequest跨域不起作用。相反,我会加载一个<img>你希望很快回来并观看onload事件的小文件:

function checkServerStatus()
{
    setServerStatus("unknown");
    var img = document.body.appendChild(document.createElement("img"));
    img.onload = function()
    {
        setServerStatus("online");
    };
    img.onerror = function()
    {
        setServerStatus("offline");
    };
    img.src = "http://myserver.com/ping.gif";
}

Edit:Cleaning up my answer. An XMLHttpRequestsolution is possible on the same domain, but if you just want to test to see if the server is online, the img load solution is simplest. There's no need to mess with timeouts. If you want to make the code look like it's synchronous, here's some syntactic sugar for you:

编辑:清理我的答案。XMLHttpRequest同域的解决方案是可以的,但是如果只是想测试一下服务器是否在线,img加载解决方案是最简单的。没有必要搞乱超时。如果你想让代码看起来像是同步的,这里有一些语法糖给你:

function ifServerOnline(ifOnline, ifOffline)
{
    var img = document.body.appendChild(document.createElement("img"));
    img.onload = function()
    {
        ifOnline && ifOnline.constructor == Function && ifOnline();
    };
    img.onerror = function()
    {
        ifOffline && ifOffline.constructor == Function && ifOffline();
    };
    img.src = "http://myserver.com/ping.gif";        
}

ifServerOnline(function()
{
    //  server online code here
},
function ()
{
    //  server offline code here
});

回答by Will P

Here's how I achieved checking server availability using Fetch to manage the request and AbortController to handle a timeout within a Node.js application.

下面是我如何使用 Fetch 来管理请求并使用 AbortController 来处理 Node.js 应用程序中的超时来检查服务器可用性。

function checkServer(url, timeout) {
  const controller = new AbortController();
  const signal = controller.signal;
  const options = { mode: 'no-cors', signal };
  return fetch(url, options)
    .then(setTimeout(() => { controller.abort() }, timeout))
    .then(response => console.log('Check server response:', response.statusText))
    .catch(error => console.error('Check server error:', error.message));
}

回答by pimvdb

Use an XMLHttpRequest, then check whether it failed. Not sure if this would work cross-domain though.

使用XMLHttpRequest,然后检查它是否失败。不确定这是否可以跨域工作。

回答by d-live

Make an ajax call and its result will tell.

进行 ajax 调用,其结果将说明问题。