首页 > 解决方案 > Fetch 无法收到大量响应

问题描述

我正在尝试获取 react-native(js),但是响应被破坏了很多次,尤其是对于更大的数据!

响应是一个数组,对于数组大小 < 5 提取通常有效,对于数组大小 > 20 提取几乎从不有效,给出以下错误:

[未处理的承诺拒绝:SyntaxError: JSON Parse error: Expected ']']

这是用于获取的代码:

        fetch(url)
        .then(response => {
            if(response.status!==200){alert('Something went wrong, please try again later');return null}
            return response.json()
        })
        .then(response => {
            if (response == null){return}
            console.log(response)
        })

错误发生在“return response.json()”行。

请帮忙!谢谢。

标签: jsonreactjsfetchresponseparse-error

解决方案


您可能需要检查从服务器发回的 json。错误发生在格式错误的 json 上。但是,这也可能是您格式化获取的方式。

这是一些从 api 获取 json 的代码。这是 matt gaunt 的文章中的一个很好的例子,https://developers.google.com/web/updates/2015/03/introduction-to-fetch#: ~:text=The%20response%20of%20a%20fetch ,%20stream%20将%20发生%20异步

fetch('./api/some.json')
  .then(
    function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      // Examine the text in the response
      response.json().then(function(data) {
        console.log(data);
      });
    }
  )
  .catch(function(err) {
    console.log('Fetch Error :-S', err);
  });

推荐阅读