json 解析空响应时 Whatwg Fetch 失败,我该如何防止它?
Whatwg Fetch fails when json parsing an empty response, how can I prevent it?
我在前端和后端 (NodeJS) 都使用了 Fetch API,在将响应解析为 json 时,我经常遇到这个问题。
response.json()
将 return 一个承诺,所以我事先不知道响应的主体是什么,当主体为空时,JSON 解析将失败并显示错误:
SyntaxError: Unexpected end of input
所以我的问题是,如何防止在响应为空时解析响应?
谢谢
为什么不使用 try catch 处理错误
try {
body = JSON.parse(body)
} catch (err) {
}
由于 response.json()
return 是一个 Promise,您可以使用 catch
和 return 一个虚拟数据对象来处理错误。
fetch('url').then(response => {
return response.json().catch(err => {
console.error(`'${err}' happened, but no big deal!`);
return {};
});
}).then(data => {
console.log(data);
});
更新
如下所述,如果您尝试读取 response
两次,您将收到错误消息:TypeError: Already Read
.
作为解决方法,您可以 clone
原始响应并在克隆对象上调用 json
。
fetch('url').then(response => {
const responseCopy = response.clone();
return responseCopy.json().catch(_ => response.text());
}).then(data => {
console.log(data);
});
获得 Response
object 后,检查 headers 并查看 Content-Length
的内容。基于此,您可以知道是否有要解析的内容。而且,服务器 return 空的 application/json
资源似乎是假的,因为那不是 JSON.
很简单,只需检查响应正文类型,如下所示:
var contentType = response.headers.get('content-type')
if (contentType && contentType.indexOf('application/json') !== -1) {
return response.json();
}else{
//if response is not json and mostly empty
return({})
}
它 return 如果响应为空则为空对象
我在前端和后端 (NodeJS) 都使用了 Fetch API,在将响应解析为 json 时,我经常遇到这个问题。
response.json()
将 return 一个承诺,所以我事先不知道响应的主体是什么,当主体为空时,JSON 解析将失败并显示错误:
SyntaxError: Unexpected end of input
所以我的问题是,如何防止在响应为空时解析响应?
谢谢
为什么不使用 try catch 处理错误
try {
body = JSON.parse(body)
} catch (err) {
}
由于 response.json()
return 是一个 Promise,您可以使用 catch
和 return 一个虚拟数据对象来处理错误。
fetch('url').then(response => {
return response.json().catch(err => {
console.error(`'${err}' happened, but no big deal!`);
return {};
});
}).then(data => {
console.log(data);
});
更新
如下所述,如果您尝试读取 response
两次,您将收到错误消息:TypeError: Already Read
.
作为解决方法,您可以 clone
原始响应并在克隆对象上调用 json
。
fetch('url').then(response => {
const responseCopy = response.clone();
return responseCopy.json().catch(_ => response.text());
}).then(data => {
console.log(data);
});
获得 Response
object 后,检查 headers 并查看 Content-Length
的内容。基于此,您可以知道是否有要解析的内容。而且,服务器 return 空的 application/json
资源似乎是假的,因为那不是 JSON.
很简单,只需检查响应正文类型,如下所示:
var contentType = response.headers.get('content-type')
if (contentType && contentType.indexOf('application/json') !== -1) {
return response.json();
}else{
//if response is not json and mostly empty
return({})
}
它 return 如果响应为空则为空对象