martasp / BlazorLiveReload

BlazorLiveReload
143 stars 14 forks source link

Fetch always giving an error: Failed to fetch TypeError: Failed to fetch #1

Closed dharmaturtle closed 4 years ago

dharmaturtle commented 5 years ago

I was getting this error: Failed to fetch TypeError: Failed to fetch

I couldn't figure out how to fix fetch, so I used this instead:

<script>
  var wait = ms => new Promise((r, j) => setTimeout(r, ms)); // Inspired by https://github.com/martasp/BlazorLiveReload
  var failed = false;
  async function fetchAsync() {
    try {
      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function () {
        if (this.status === 200 && failed) { // connected and previously failed
          location.reload();
        } else if (this.status === 0 && this.readyState === 4) { // connection broken
          failed = true;
        }
      };
      xhttp.open("GET", "/", true);
      xhttp.send();
    }
    catch (e) {
      failed = true;
      await wait(200);
      console.log("failed " + e);
    }
  }
  async function Pooling() {
    while (true) {
      fetchAsync();
      await wait(200);
    }
  }
  Pooling();
</script>

That's all!

I'd also suggest people put the above in an <environment include="Development"> tag