如何使用javascript的获取方法捕获401错误 [英] How to catch 401 error using fetch method of javascript

查看:108
本文介绍了如何使用javascript的获取方法捕获401错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要捕获错误401响应代码,以便从令牌端点获取新令牌后可以重试.我正在使用提取方法从API获取数据.

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.

   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
        });

推荐答案

由于 401 实际上是对服务器请求的有效响应,因此无论执行什么操作,它都会执行您的有效响应.仅当发生安全问题,或者服务器无响应或根本不可用时,才会使用 catch 子句.只需将其视为尝试与某人交谈即可.即使他们说我目前不可用"或我没有该信息",您的对话仍然成功.仅当安全人员介入您之间并且阻止您与收件人交谈时,或者收件人为时,对话才会真正失败,您需要使用 catch .

Because 401 is 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 catch clause 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.

只需将您的错误处理代码分离出来,以便您可以在请求成功但没有预期结果的情况下进行处理,例如当抛出实际错误时,以及:

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 well as 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 );

我正在使用@Noface在注释中建议的 response.ok ,因为这很有意义,但是您只能检查 response.status === 401 如果需要的话.

I am using the response.ok suggested by @Noface in the comments, as it makes sense, but you could check for only the response.status === 401 if you want to.

这篇关于如何使用javascript的获取方法捕获401错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆