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

Ski*_*zit 15 javascript

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

我尝试过以下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;
    }   
}
Run Code Online (Sandbox Code Playgroud)

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

gil*_*ly3 26

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";
}
Run Code Online (Sandbox Code Playgroud)

编辑: 清理我的答案.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
});
Run Code Online (Sandbox Code Playgroud)

  • @gurehbgui - 用CSS隐藏它.例如:`img.style.display ="none";` (2认同)
  • 如果我错了,请纠正我,但是当我们向其他服务器发送请求时,除非我们知道服务器中图像的地址,否则它将失败...?他们可以随时删除图像...我不明白使用图像有什么好处,因为如果我们控制服务器,我们可以发送跨域XMLHttpRequest. (2认同)

小智 6

下面是我如何使用 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));
}
Run Code Online (Sandbox Code Playgroud)