json - 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()”行。
请帮忙!谢谢。
解决方案
您可能需要检查从服务器发回的 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);
});
推荐阅读
- javascript - React map() 显示未定义
- gradle - gradle如何排除重复的资源文件?
- ruby-on-rails - Rails:jQuery ajax() 正在返回所有 html
- python - 使用时间戳对 Python 字典列表进行排序
- javascript - 在 Flutter 中构建 d3.js 小部件
- javascript - 引导表 Javascript 总和变成 NaN?
- linux - Linux - Git Credentials - 如何删除用户名/密码组合的实例?
- ruby-on-rails - 让用户调整“存在”验证?
- javascript - js 脚本未在 Git Hub 页面上加载
- neo4j - Neo4j:Cypher 查询如何将结果与仅包含在数组中的值匹配