代码之家  ›  专栏  ›  技术社区  ›  Chris Calo SheetJS

检测xhr状态在axios中===0

  •  0
  • Chris Calo SheetJS  · 技术社区  · 6 年前

    我有一个在公司环境中运行的web应用程序,所有请求都通过一个我无法控制的代理。此层会根据需要自动将我的用户重定向到不同域上的单个登录页。

    1. 用户类型 myapp.example.corp 进入他们的浏览器
    2. 请求通过代理进行,代理检查用户是否已登录
    3. 用户未登录,因此将重定向到登录位置 auth.example.corp
    4. 用户登录,然后重定向到我的应用程序

    问题

    1. 用户在我的应用程序中做了一些工作,然后回家,打开浏览器选项卡
    2. 当我的应用程序打开时,用户返回浏览器选项卡并继续使用它
    3. 我的应用程序发出AJAX请求,它们通过同一个代理
    4. 由于用户不再登录,这些请求将重定向到登录页
    Failed to load https://auth.example.corp: No 'Access-Control-Allow-Origin'
    header is present on the requested resource. Origin 'https://myapp.example.corp'
    is therefore not allowed access.
    

    (这个问题与CORS无关。我无法控制代理服务器或身份验证服务器。请不要分心。)

    // none of these callbacks get called
    axios
      .get("/signedin")
      .then(response => console.log("Signed in"))
      .catch(response => console.log("Not signed in"))
    

    变通办法

    如果我用 XMLHttpRequest API,我能发现这种情况是因为 onreadystatechange 事件激发,我可以测试 request.status === 0 .

    var request = new XMLHttpRequest();
    request.onreadystatechange = event => {
      if (request.readyState === 4 && request.status === 0) {
        console.log("Not signed in");
      }
    };
    request.open("GET", "/signedin");
    request.send();
    

    所以我的问题是:我真的很想继续使用axios,但能够检测到这种情况。有什么方法可以探测到 xhr.status == 0 使用axios时,还是我被迫使用

    1 回复  |  直到 6 年前
        1
  •  2
  •   Vinay    6 年前

    CORS是一个问题,每当飞行前请求失败时,浏览器将完全拒绝访问返回状态码、响应主体和头。那个这就是为什么axios永远不会知道这一点,也可能是承诺没有实现的原因—这有点类似于没有任何超时限制的网络故障。

    axios.interceptors.response.use((response) => response, (error) => {
      if (typeof error.response === 'undefined') {
          //alert the failure
      }
      return Promise.reject(error);
    });