简体   繁体   English

存在休息时,响应文本始终为空事件

[英]Response text is always empty event when repose exist

  1. I am fetching the PDF via URL, and want to check does that URL will return the document successfully.我正在通过 URL 获取 PDF,并想检查该 URL 是否会成功返回文档。

  2. Sending a request via fetch()通过fetch()发送请求

  3. Get a response.text()获取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. response.text()始终返回空文本,即使响应中存在 PDF 文档。


  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);
      });
  };

Note that res => res.text() means read the body as a string.请注意, res => res.text()表示将正文作为字符串读取。 So it is good idea to use response.json() before you access to response.因此,在访问响应之前使用response.json()是个好主意。 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.另请参阅答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM