我构建了一个 react-native 应用程序并使用 fetch api用于处理服务器请求,如果从服务器返回的 json 不为空,它工作正常,但如果来自服务器的响应为空,它会给我一个错误 - “Json Parse error:Unexpected EOF”,下面是使用的代码我为了获取,我尝试在调试时设置断点以查看从服务器返回 null 时响应的内容,我无法找到可以在解析之前检查响应是否为 null 的内容,所以需要帮助
return fetch(url, //service url{
method: type, // get or post
headers: {
'Accept': 'application/json',
'Content-Type': contentType,
},
body: data //some input parameters
}).then((response) => {
return response.json();
})
.then((responseJson) => {
request.onSuccess(responseJson); // success callback
})
.catch((error) => {
request.onError(error); // error callback
console.error(error);
});
最佳答案
有好答案here ,但在我的情况下,我需要在 response.text() 返回后访问响应对象:
function buildResult(response) {
// response.json() crashes on null response bodies
// return {
// data: response.json(),
// identityToken: response.identityToken // sliding expiration...
// };
return new Promise((resolve, reject) => {
response.text().then(body => {
resolve({
data: body.length ? JSON.parse(body) : null,
identityToken: response.identityToken // sliding expiration...
});
}).catch(err => {
reject(err);
});
});
}
//
// the api fetch function
//
function apiFetch(url) {
return fetch(url)
.then(checkStatus)
.then(parseIdentityToken)
.then(buildResult);
}
关于javascript - 如何在 fetch api 中处理空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39399051/