axios拦截器响应未定义 [英] axios interceptors response undefined

查看:361
本文介绍了axios拦截器响应未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户获得401后注销我的用户。我正在使用axios从api返回数据

I'm trying to logout my user once they get a 401. I'm using axios to return data from the api

我环顾四周并找到了相同的axios.interceptors.response

I was looking around and found the same axios.interceptors.response

  axios.interceptors.response.use(
    response => response,
  error => {
    const {status} = error.response;
    if (status === 401 ) {
      store.dispatch('snackBar', snackbarObj)
    } 
   return Promise.reject(error);
  }
)

看来我的错误。回复未定义。我不确定有什么问题?有任何想法吗?

It appears my error.response is undefined. I'm not sure what is wrong? any ideas?

推荐答案

由于浏览器在执行预检时收到了401未经授权的响应 OPTION 请求,导致您尝试执行的请求出现网络错误

You're not getting a response from the request you're doing with Axios since the browser received a 401 unauthorized response when doing the preflight OPTION request, resulting in a Network Error for the request you're trying to do.

这与 CORS 的工作方式以及后端如何处理 OPTION 请求。要了解后端服务器应如何处理预检请求,了解引入预检请求的动机是什么非常重要。

This is related to how CORS works and how your backend handles OPTION requests. To understand how the backend server should handle preflight requests, it's important to understand what is the motivation behind introducing preflight requests.

后端服务器不应检查 OPTION 请求的身份验证,它应该验证是否正在向端点发出请求接受跨域请求并返回成功代码。

The backend server should not check for authentication on OPTION requests, it should validate that the request is being made to an endpoint that accepts cross-domain requests and return a success code if it does.

然后,浏览器将自动继续执行最初预期的请求。

Then, automatically, the browser will proceed with the initially intended request.

这样,如果不再对用户进行身份验证,Axios拦截器将收到401错误代码。

That way, the Axios interceptor will receive the 401 error code if the user is no longer authenticated.

无耻的自我推销,我发布了一个简单的Axios插件,名为 axios-middleware 有助于在更大的应用程序中抽象使用Axios拦截器。它提供了一个示例通过尝试进行身份验证来自动处理未经身份验证的请求的中间件再次重新发送请求之前。

Shameless self-promotion, I've published a simple Axios plugin called axios-middleware which helps abstract the use of Axios interceptors in bigger apps. It offers an example of middleware that automatically handles unauthenticated requests by trying to authenticate again before resending the request.

这篇关于axios拦截器响应未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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