当状态为 500 不工作时从获取 api 获取服务器错误消息
Getting the server error message from the fetch api when status is 500 not working
我的服务器返回 500 状态错误,我正在尝试记录服务器返回的确切错误。
这是我的尝试。 (摘自)
fetch(fetchUrl)
.then(res => {
// Check if response has errors
if (res.ok) {
// No errors
return res.json();
} else {
// Has errors, since res.json() returns a Promise, we
// chain a then here to get the value and return the err value
// as Promise rejection so that it will go to the
// catch handler
return res.json().then(err => Promise.reject(err));
// this could also be
// return res.json().then(err => throw Error(err));
}
})
.then(json => {
// dispatch success
})
.catch(err => {
console.log(err);
});
然而,当我运行上面的代码时,我得到一个错误
SyntaxError: Unexpected end of JSON input
这是为什么。如何查看服务器返回的错误。
(如果有任何不同,我正在使用 React)。
Unexpected end of JSON input
错误意味着将服务器响应的正文从文本转换为 JS 对象时出错。
这意味着响应无效 JSON。
如果您使用的是浏览器,那么最简单的方法就是查看浏览器开发控制台的网络选项卡并查看原始响应。
如果您不是,或者您想以编程方式执行此操作,则可以使用 res.text()
而不是 res.json()
。
我的猜测是您的服务器的响应主体类似于:
My code did an oopsie
这是无效的JSON。
有效的 JSON 将是
"My code did an oopsie"
然后可以将其转换为字符串。
我的服务器返回 500 状态错误,我正在尝试记录服务器返回的确切错误。
这是我的尝试。 (摘自
fetch(fetchUrl)
.then(res => {
// Check if response has errors
if (res.ok) {
// No errors
return res.json();
} else {
// Has errors, since res.json() returns a Promise, we
// chain a then here to get the value and return the err value
// as Promise rejection so that it will go to the
// catch handler
return res.json().then(err => Promise.reject(err));
// this could also be
// return res.json().then(err => throw Error(err));
}
})
.then(json => {
// dispatch success
})
.catch(err => {
console.log(err);
});
然而,当我运行上面的代码时,我得到一个错误
SyntaxError: Unexpected end of JSON input
这是为什么。如何查看服务器返回的错误。
(如果有任何不同,我正在使用 React)。
Unexpected end of JSON input
错误意味着将服务器响应的正文从文本转换为 JS 对象时出错。
这意味着响应无效 JSON。
如果您使用的是浏览器,那么最简单的方法就是查看浏览器开发控制台的网络选项卡并查看原始响应。
如果您不是,或者您想以编程方式执行此操作,则可以使用 res.text()
而不是 res.json()
。
我的猜测是您的服务器的响应主体类似于:
My code did an oopsie
这是无效的JSON。
有效的 JSON 将是
"My code did an oopsie"
然后可以将其转换为字符串。