我正在使用fetch来进行返回JSON数据的API调用 .
有时API调用会返回内容的状态 OK
和 null
. 我依靠检查状态来获取内容,但这给了我一个错误,因为没有JSON数据 .
我得到的错误是: Uncaught (in promise) SyntaxError: Unexpected end of JSON input
这是我的典型获取模式,显然我需要通过添加一个JSON数据检查来改进它 . 我该怎么修改呢?
export const getSomeData = () => {
return (dispatch) => fetch('/api/myapifunction', fetchOptionsGet())
.then((response) => {
if(response.ok) {
// I need to add logic here to check for JSON data before calling parseJSON
parseJSON(response)
.then(data => {
// Do something
})
} else {
// Failed
// Handle failure
}
})
}
我为fetchOptions创建了函数,例如GET或POST以及parseJSON . 它们功能简单 . 这就是parseJSON的样子:
export const parseJSON = (response) => {
return response.json();
}
据我了解,response.json()只是一个承诺,不一定是数据 . 如何检查我是否收到任何JSON数据?
2 回答
如果浏览器能够将响应内容解析为有效的json,则
response.json()
promise将正确运行并进入.then
部分 .如果它无法这样做 - 您可以使用
.catch
来查看问题所在:这里的诀窍是你的服务有点双重 . 它's saying it' s
OK
,但后来根本不发送任何字节 .JSON.parse('')
抛出同样的错误 .您可以使用
catch
作为Dekel注释解决此问题,或者您可以使用response.text()
:这基本上检查返回的字符串值 . 如果没有返回任何内容,它将为您提供一个空对象而不是抛出错误 . 这将有助于区分由于数据错误而导致的JSON解析错误,而根本没有数据 .