0

I am getting an error:

[SyntaxError: JSON Parse error: Unexpected identifier "undefined"]

I am trying to do 2 API calls because one depends on the other.

Code:

      const bearer = "Bearer " + user?.token;

      fetch(`${API}/getDocumentById`, {
        method: "POST",
        headers: {
          Authorization: bearer,
          "X-Requested-With": "XMLHttpRequest",
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ document_id: doc.id }),
      })
        .then((response) => response.json())
        .then((json) => {
          console.log(`${API}/viewFile?file=${json.document.file}`);
          // This console logs returns a good value:
          // http://my-api.com/api/viewFile?file=1620802187_MAPPA-definitiva.pdf
          fetch(`${API}/viewFile?file=${json.document.file}`, {
            method: "GET",
            headers: {
              Authorization: bearer,
              "X-Requested-With": "XMLHttpRequest",
            },
          })
            .then((response) => response.json())
            .then((json) => {
              setImage(json.document);
            })
            .catch((viewFileError) => {
              // HERE IS WHERE IT THROWS THE ERROR
              console.log({ viewFileError });
            });

          setData(json.document);
        })
        .catch((err) => {
          setLoading(false);
          console.log({ err });
        });

On Postman it works properly.

enter image description here

What am I doing wrong?

Headers: enter image description here

Reacting
  • 5,543
  • 7
  • 35
  • 86
  • 1
    ah ,wait the response is not format json. Fetch api can decode the bytesteram to more than ust json. response.json() must call internally json .parse. – The Fool May 21 '21 at 20:51
  • 2
    Does this answer your question? [Requesting blob images and transforming to base64 with fetch API](https://stackoverflow.com/questions/44698967/requesting-blob-images-and-transforming-to-base64-with-fetch-api) – The Fool May 21 '21 at 20:52
  • hm, looks like you are fetching pdf actually. Maybe this https://gist.github.com/devloco/5f779216c988438777b76e7db113d05c – The Fool May 21 '21 at 20:53
  • @TheFool mmm how is that? Did you check the Postman screenshot? Postman returns just what I need. So I don't get how is that my code doesn't work. – Reacting May 21 '21 at 21:08
  • Your console output is telling you. ` console.log(`${API}/viewFile?file=${json.document.file}`); // This console logs returns a good value: // http://my-api.com/api/viewFile?file=1620802187_MAPPA-definitiva.pdf` – The Fool May 21 '21 at 21:09
  • you can also use postman to help you to generate the code btw. It will at least show you how its decoding the pdf. – The Fool May 21 '21 at 21:14
  • @Reacting The postman screenshots shows us that the response to the second request is certainly not JSON. You can check the response headers to confirm. – Bergi May 21 '21 at 21:18

0 Answers0