我正在使用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数据?