【问题标题】:Vue-axios interceptor 401 errorVue-axios拦截器401错误
【发布时间】:2018-04-25 20:11:07
【问题描述】:

由于令牌过期,api 给出 401 Unauthorized 错误。

尽管如此,错误状态码(401) 在 axios 拦截器中不可用。

Vue.axios.interceptors.response.use(function(response) {    
  return response;
}, function(error) {

    // I want to catch the 401 error here but, error.response is undefined
    return Promise.reject(error);
});

我有什么办法可以得到它,下面的github issueerror.response.status 可以使用,但 error.response 对我来说是未定义的

Http 错误: 无法加载http://localhost:5000/api/user:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'http://localhost:2323'。响应的 HTTP 状态代码为 401。

来自拦截器 response.use 的 Console.log(error) 错误:网络错误 在 createError (createError.js:16) 在 XMLHttpRequest.handleError (xhr.js:87)

【问题讨论】:

  • 可以先把错误记录下来吗?
  • @samayo 错误日志已更新。
  • 您在两个不同的端口之间发出请求。这是一个 CORS 问题。您需要允许您的后端接受或添加Access-Control-Allow-Origin 选项
  • 在实际请求之前触发飞行前请求我猜这就是为什么您永远无法拦截错误响应的原因。
  • @VaisakhRajagopal 你找到方法了吗?我还需要拦截 401,以便我可以重定向到登录屏幕。

标签: vue.js interceptor axios


【解决方案1】:

这是我的 Axios 错误处理程序代码。它运行。 如果需要,您可以删除 toast 代码。

    import axios from 'axios'
    import toast from './toast'
    import store from '../../store'
    
    // apply interceptor on response
    axios.interceptors.response.use(function (response) {
      if (response.status === 200 && response.data.message) {
        toast.success(response.data.message)
      }
      if (response.status === 201 && response.data.message) {
        toast.success(response.data.message)
      }
      return response
    }, function (error) {
      // Do something with response error
      // check for errorHandle config
    
      // if has response show the error
      if (error.response) {
        if (error.response.status === 404 || error.response.status === 400) {
          toast.error(error.response.data.message)
        }
        if (error.response.status === 401) {
          // if you ever get an unauthorized, logout the user
          store.dispatch('logout')
        // you can also redirect to /login if needed !
        }
      }
      return Promise.reject(error)
    })

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 2019-03-27
    • 1970-01-01
    • 2021-06-29
    • 2019-02-11
    • 2022-11-20
    • 2020-07-20
    • 2014-11-02
    • 2018-11-27
    相关资源
    最近更新 更多