0

So I am creating a website. And I want the user to be able to download files. And so I made this script

var dwnldBtn = document.getElementById("downloadButton");
var filename = "";
var ext = "";
var title = document.getElementsByTagName("title")[0].innerText.split(" ");

async function FetchTheRest() {
  fetch(`https://pathToFile`)
    .catch((err) => {
      console.log("err");
    })
    .then((res) => res.blob())
    .then((blob) => {
      document.body.append(anchor);
      anchor.style = "display: none;";

      var url = window.URL.createObjectURL(blob);
      anchor.href = url;
      anchor.download = filename;

      dwnldBtn.style = "background-color: #00ff00;";
    });
}

async function getEXT() {
  var JSON = await fetch("https://pathToFile.json").then((result) => {
    return result.json();
  });
  JSON.versions.forEach((version, index) => {
    if (version.version == title[4]) {
      ext = version.ext;
    }
  });
  if (ext != "") {
    filename = "DSGM " + title[4] + "." + ext;
    document.getElementById("NameOfFile").innerHTML = filename;
    FetchTheRest();
  }
}

getEXT();

var anchor = document.createElement("a");

dwnldBtn.addEventListener("click", function () {
  anchor.click();
});

But when I run this, it sometimes works, and other times it gives me these errors:

Error 1:

Uncaught (in promise) TypeError: Failed to fetch
Promise.then (async)
FetchTheRest @ downloader.js:12
getEXT @ downloader.js:37
await in getEXT (async)
(anonymous) @ downloader.js:41

Error 2:

downloader.js:7          GET https://pathToFile net::ERR_FAILED 200
FetchTheRest @ downloader.js:7
getEXT @ downloader.js:37
await in getEXT (async)
(anonymous) @ downloader.js:41

NOTE: the files that I get this error on are bigger files. So I don't know if that has anything to do with it.

Also you will see in the getEXT function, there is a fetch (not the one giving errors). This fetch is getting a JSON file with needed information in it. Like the version number (of file), image (preview image), and ext (the file extension).

Phil
  • 157,677
  • 23
  • 242
  • 245
  • Do you see any hints in your browser dev-tools _Network_ panel? – Phil Oct 26 '22 at 03:21
  • by hints, what am I exactly looking for? – BowersIndustry Oct 26 '22 at 03:25
  • What are the responses to the failed requests? Are there responses at all? I don't think there's anything particularly wrong with your client-side JS code (other than `.catch()` should be the last item in the promise chain) – Phil Oct 26 '22 at 03:27
  • if you mean from the .catch, I get "TypeError: Failed to fetch" – BowersIndustry Oct 26 '22 at 03:29
  • No, not quite. I meant you shouldn't use `.catch()` before `.then()` unless the `.catch()` callback produces a new resolved value. Typically you'd use `fetch().then().then().catch()` – Phil Oct 26 '22 at 03:30
  • I see. It seems that the `(res) => res.blob()` is what is making everything go down hill. – BowersIndustry Oct 26 '22 at 03:34
  • You should check `res.ok` before trying to parse the response body. See [Fetch: reject promise and catch the error if status is not OK?](https://stackoverflow.com/a/38236296/283366) – Phil Oct 26 '22 at 03:36
  • I got it to work. Thank you! I will send the solution as an answer. – BowersIndustry Oct 26 '22 at 03:46

1 Answers1

0

This worked for me.

fetch(`https://pathToFile`)
            .then((response) => {
                if (response.ok) {
                    return response.blob();
                }
                throw new Error('Something went wrong');
            })
            .then((blob) => {
                document.body.append(anchor);
                anchor.style = "display: none;"

                var url = window.URL.createObjectURL(blob)
                anchor.href = url;
                anchor.download = filename;

                dwnldBtn.style = "background-color: #00ff00;"
            })
            .catch((err) => {
                console.log(err)
            });