Fetch 无法收到大量响应

问题描述

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

响应是一个数组,对于数组大小 20 fetch 几乎从不工作,给出以下错误

[未处理的承诺拒绝: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()' 行。

请帮忙!谢谢。

解决方法

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

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

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