Is it possible to ping a server from Javascript?

后端 未结 17 1180
礼貌的吻别
礼貌的吻别 2020-11-22 04:02

I\'m making a web app that requires that I check to see if remote servers are online or not. When I run it from the command line, my page load goes up to a full 60s (for 8 e

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 04:46

    const ping = (url, timeout = 6000) => {
      return new Promise((reslove, reject) => {
        const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
        if (!urlRule.test(url)) reject('invalid url');
        try {
          fetch(url)
            .then(() => reslove(true))
            .catch(() => reslove(false));
          setTimeout(() => {
            reslove(false);
          }, timeout);
        } catch (e) {
          reject(e);
        }
      });
    };
    

    use like this:

    ping('https://stackoverflow.com/')
      .then(res=>console.log(res))
      .catch(e=>console.log(e))
    

提交回复
热议问题