Javascript 如何使用javascript的fetch方法捕获401错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49902417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to catch 401 error using fetch method of javascript
提问by Vikrant Singh
I need to catch error 401 Code of response so that I can retry after getting a new token from token endpoint. I am using fetch method get data from API.
我需要捕获错误 401 响应代码,以便在从令牌端点获取新令牌后重试。我正在使用 fetch 方法从 API 获取数据。
const request: Request = new Request(url.toString(), {
headers: this.defaultRequestHeaders,
method: "get",
mode: "cors"
});
const headers: Headers = new Headers({
"Accept": "application/json",
"Content-Type": "application/json"
});
fetch(request)
.then(function(response)
{
///Logic code
})
.catch(function(error)
{
///if status code 401. Need help here
});
回答by Israel kusayev
You can check the status and if it's not 200 (ok) throw an error
您可以检查状态,如果不是 200 (ok) 则抛出错误
fetch("some-url")
.then(function(response)
{
if(response.status!==200)
{
throw new Error(response.status)
}
})
.catch(function(error)
{
///if status code 401...
});
回答by Salman Saleem
You can try this
你可以试试这个
fetch(request)
.then(function(response) {
if (response.status === 401) {
// do what you need to do here
}
})
.catch(function(error) {
console.log('DO WHAT YOU WANT')
});
回答by somethinghere
Because 401is actually a valid response to a request to a server, it will execute your valid response regardless. Only if security issues occur, or if the server is unresponsive or simply not available will the catchclause be used. Just think of it like trying to talk to somebody. Even if they say "I am currently not available" or "I don't have that information", your conversation was still successful. Only if a security guy comes in between you and stops you from talking to the recipient, or if the recipient is dead, will there be an actual failure in conversation and will you need to respond to that using a catch.
因为401实际上是对服务器请求的有效响应,所以无论如何它都会执行您的有效响应。只有在出现安全问题,或者服务器无响应或根本不可用时,catch才会使用该子句。把它想象成试图与某人交谈。即使他们说“我目前不可用”或“我没有该信息”,您的对话仍然是成功的。只有当保安人员挡在您之间并阻止您与接收者交谈时,或者接收者已死时,才会出现真正的对话失败并且您需要使用catch.
Just separate out your error handling code so you can handle it in instances that the request was successful, but does not have the desired outcome, as wellas when an actual error is being thrown:
只需将您的错误处理代码分开,以便您可以在请求成功但没有预期结果的情况下处理它,以及在抛出实际错误时:
function catchError( error ){
console.log( error );
}
request.then(response => {
if( !response.ok ){
catchError( response );
} else {
... Act on a successful response here ...
}
}).catch( catchError );
I am using the response.oksuggested by @Noface in the comments, as it makes sense, but you could check for only the response.status === 401if you want to.
我response.ok在评论中使用了@Noface 建议的,因为它是有道理的,但您可以仅检查response.status === 401是否需要。
回答by Dario
You can check the statusof the response in then:
您可以在以下位置检查status响应then:
fetch(request)
.then(function(response) {
if (response.status === 401) {
// do what you need to do here
}
})
.catch(function(error) {});
回答by Mohammad Sabbagh
(function () {
var originalFetch = fetch;
fetch = function() {
return originalFetch.apply(this, arguments).then(function(data) {
someFunctionToDoSomething();
return data;
});
};})();
source Can one use the Fetch API as a Request Interceptor?
source 可以使用 Fetch API 作为请求拦截器吗?
回答by Aleksandar Panov
When you want to...
当你想...
catch (error) {
console.dir(error) // error.response contains your response
}

