我使用whatwg-fetch发出请求,并且我正在尝试检查response.status === 0
以防response.ok
为false,以查看服务器当前是否处于脱机状态并相应地通知用户。
问题是,当服务器脱机时,response.status
始终为200,response.ok
始终为真。
const interpretJsonResponse = (response, callback):object => {
const responseClone = response.clone();
if (response.ok) {
response.json().then((json) => callback(null, respondJson(json))).catch(callback);
} else {
// Response is not ok. Callback with a generic error to show to the user
// and log the error for detailed info
if (response.status === 0) {
// Backend server is not up
callback('Backend server is not responding. Please retry later!');
} else {
callback(`Error in request: ${response.statusText}`);
}
}
// Return a clone to allow usage of .json() again if necessary
return responseClone;
};
由于缺少要回复的服务器,因为响应为空,我也收到了JSON解析错误。我/我可以缺少什么?
示例响应对象:
"url":"http://localhost:8000/client_v1/auth/",
"status":200,
"statusText":"OK",
"headers": {}
"ok":true,
"body":{
"_readableState":{
"highWaterMark":16384,
"buffer":[],
"length":0,
"pipes":null,
"pipesCount":0,
"flowing":null,
"ended":false,
"endEmitted":false,
"reading":false,
"sync":false,
"needReadable":true,
"emittedReadable":false,
"readableListening":false,
"objectMode":false,
"defaultEncoding":"utf8",
"ranOut":false,
"awaitDrain":0,
"readingMore":false,
"decoder":null,
"encoding":null
},
"readable":true,
"_events":{},
"_writableState":{
"highWaterMark":16384,
"objectMode":false,
"needDrain":false,
"ending":false,
"ended":false,
"finished":false,
"decodeStrings":true,
"defaultEncoding":"utf8",
"length":0,
"writing":false,
"corked":0,
"sync":true,
"bufferProcessing":false,
"writecb":null,
"writelen":0,
"buffer":[
],
"pendingcb":0,
"prefinished":false,
"errorEmitted":false
},
"writable":true,
"allowHalfOpen":true,
"_transformState":{
"needTransform":false,
"transforming":false,
"writecb":null,
"writechunk":null
}
},
"bodyUsed":false,
"size":0,
"timeout":0,
"_raw":[],
"_abort":false
编辑:添加完整功能 编辑#2:添加了示例whatwg-fetch响应对象
答案 0 :(得分:0)
我刚刚在fetch中找到了这个警告,这可能对您有用:
Caveats
The fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:
The Promise returned from fetch() won't reject on HTTP error status even if the response is a HTTP 404 or 500. Instead, it will resolve normally, and it will only reject on network failure, or if anything prevented the request from completing.
所以,我应该简单地检查响应是否为空(如果响应为空,如你所说):
if (response === null) {
return callback('Empty reponse from backend server. Please retry later!');
}
if (response.ok) {
...