2
  1. I am fetching the PDF via URL, and want to check does that URL will return the document successfully.

  2. Sending a request via fetch()

  3. Get a response.text()

  4. Want to check does text exist

  5. Text is always empty

Cannot figure out why?

response.text() always returns empty text, even when PDF document exist in response.


  const handleOpenPDF = (url: any) => {
    fetch(url, {
      method: 'GET',
      mode: 'no-cors',
    })
      .then(res => res.text())
      .then(text => {
    enter code here
        // TEXT is always empty event when response is good
        console.warn('text', text);

        window.open(url, '_blank');
      })
      .catch(err => {
        console.warn('Error', err);
      });
  };
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
Mark James
  • 338
  • 4
  • 15
  • 43
  • How about using `response.json()` instead of `res => res.text()`? – Alireza Ahmadi Oct 20 '21 at 10:46
  • Do you actually need `mode: 'no-cors',`? this can cause a problem sometimes. see [this answer](https://stackoverflow.com/questions/35169728/redux-fetch-body-is-not-use-with-no-cors-mode/35291777#35291777) – Alireza Ahmadi Oct 20 '21 at 10:52
  • @AlirezaAhmadi I am gonna try to avoid "mode: no cors", but not sure that I will succed – Mark James Oct 20 '21 at 10:57

1 Answers1

1

Note that res => res.text() means read the body as a string. So it is good idea to use response.json() before you access to response. something like this:

const handleOpenPDF = (url: any) => {
    fetch(url, {
      method: 'GET',
      mode: 'no-cors',
    })
      .then(res => res.json())
      .then(text => {
        console.warn('text', text);

        window.open(url, '_blank');
      })
      .catch(err => {
        console.warn('Error', err);
      });
  };

Also see this answer.

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42