这个问题在这里已经有了答案:
How to handle HTTP code 4xx responses in fetch api
(4 个回答)
Handle a 500 response with the fetch api
(1 个回答)
try..catch not catching async/await errors
(1 个回答)
1年前关闭。
我正在使用 fetch api 发送请求并根据结果正确或包含错误进行操作。
我的服务代码:
LoginUser(user: User) {
return fetch("http://localhost:8080/login", {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(user)
});
}
和我的then-catch
调用上述代码的代码是:async loginUser() {
let response = await this._service.LoginUser(this.user)
.then(response => {return response.json()})
.then(response => {this._router.navigate(['/mainpage'])})
.catch(error => {alert(error)});
}
响应是否带有代码 500 Internal Server Error 仍然重定向到 /mainpage
并且不识别错误。我该如何解决这个问题?
最佳答案
当一个 fetch
请求从服务器返回一个错误代码 catch
的 promise 未执行,then
是。 catch
仅在网络故障时执行。见 the fetch docs :
The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
你需要做的是,在你的
then
, 检查 response.ok
.如果 response.ok == false
,然后请求返回错误。您可以在 response.status
中找到有关此错误的信息。和 response.statusText
.
关于javascript - 获取 api 请求时如何捕获错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63103029/