【问题标题】:Response undefined for 302 status axios未定义 302 状态 axios 的响应
【发布时间】:2019-06-27 06:50:58
【问题描述】:

我正在使用带有 typescript 的 axios。

我有一个简单的 axios 拦截器,编码如下。

// Add a response interceptor
axios.interceptors.response.use((response: AxiosResponse<any>) => {
  // Do something with response data
  return response;
}, (error: any) => {
  // Do something with response error
  // Here "error.response" is undefined. 
  return Promise.reject(error);
});

我想要做的是在未经身份验证时需要重定向到其他位置(身份服务器 SSO 页面,但我猜这与这里无关)。

所以当调用我的 API 时,如果没有通过正确的位置进行身份验证,则会返回 302 状态代码。

但是 axios 不会自动重定向到那个位置。

如果我必须手动重定向,那仍然可以。

但我将“error.response”视为未定义。

那么现在我该如何重定向?因为“error.response”未定义,我无法检测到状态码。

在网络选项卡中显示如下。

响应选项卡显示以下内容。没有可用的响应数据...!!!

我做错了什么?

【问题讨论】:

  • console.log(error)你看到了什么?
  • 错误:在 XMLHttpRequest.handleError (xhr.js?b50d:87) 的 createError (createError.js?2d83:16) 处出现网络错误
  • 所以console.dir(error),打开属性并尝试在那里找到状态
  • 我这样做了,它不起作用。

标签: ajax typescript axios identityserver4


【解决方案1】:

据我了解,302 代码由浏览器处理。回答 302 后,浏览器会收到 location header 传递的页面,并将其传递给 Axios。所以你可以在response.data 中找到页面html。同样在response.request.responseURL 中,您可以找到需要重定向到的 URL。

所以我做了这样的事情:

axios.post('.', Data)
     .then(response => {
         if (response.status === 200) {
             window.location.href = response.request.responseURL;
         }
     })
     .catch(error => {console.log(error)});

现在对我有用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2021-11-02
    • 2020-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    相关资源
    最近更新 更多