Vue + Axios 处理来自服务器的所有请求错误

Posted

技术标签:

【中文标题】Vue + Axios 处理来自服务器的所有请求错误【英文标题】:Vue + Axios handling error from server for all request 【发布时间】:2021-06-25 06:40:07 【问题描述】:

我正在使用 Vue + Axios + Vue 路由器 + Vuex。

我想在Vue中处理身份验证,登录后,用户可以做任何事情。但有时令牌会过期,服务器会给出错误,比如说Code = 123。我想要的是,如果服务器给我Code = 123,我想将用户重定向到登录页面。我可以检查 axios 的每个响应,但它并不有效,因为有数百个 axios 请求会影响。

问题:

    如果服务器给出一些错误代码如Code = 123,如何重定向?这发生在数百个 axios 响应中。

请注意:

    是服务器端检查,服务器可以撤销令牌等,所以前端无法阻止令牌过期。 我不想在 axios 中手动检查数百个响应。如果我能在一个地方处理它会很棒,所以如果我进行重构,它会很容易做到。

【问题讨论】:

【参考方案1】:

@thegrass,您可以在全局级别配置 axios 并访问应用程序内部的 axios

全局配置使用请求、响应拦截器

应用程序触发的任何请求都将通过此请求拦截器,响应来自响应拦截器

如果您在响应拦截器中有逻辑说明响应代码是否为 123,则删除存储在客户端的访问令牌并将用户重定向到登录页面

请找到示例 axios 拦截器(您还可以阅读有关在 vue js 应用程序中设置 axios 全局拦截器的更多信息

在 axios-config.js 文件中

import axios from 'axios';

const http = axios.create();

/* Response Interceptors */
const interceptResErrors = (err) => 
  try 
    // check for response code 123 and redirect to login
    err = Object.assign(new Error(), message: err.response.data);
   catch (e) 
    // check for response code 123 and redirect to login
    // Will return err if something goes wrong
  
  return Promise.reject(err);
;
const interceptResponse = (res) => 
  try 
    // check for response code 123 and redirect to login
    return Promise.resolve(res.data);
   catch (e) 
    // check for response code 123 and redirect to login
    return Promise.resolve(res);
  
;
http.interceptors.response.use(interceptResponse, interceptResErrors);

/* Request Interceptors */
const interceptReqErrors = err => Promise.reject(err);
const interceptRequest = (config) => 
  return config;
;
http.interceptors.request.use(interceptRequest, interceptReqErrors);

export default http;

此文件导出 HTTP 客户端 axios 对象,您可以将其导入或挂载到 main.js / app.js 中的 Vue 实例,如下所述

从 axios-config.js 导入 http

Vue.prototype.$api = http;

在你的组件内部

this.$api.get('/some-api');

【讨论】:

感谢您的回答,好的,收到错误代码后,如何从 axios-config.js 重定向到登录页面? @thegrass,希望这个答案能帮助***.com/questions/52948253/…

以上是关于Vue + Axios 处理来自服务器的所有请求错误的主要内容,如果未能解决你的问题,请参考以下文章

Django+vue前后端分离 用axios post请求报错问题

VUE使用axios数据请求时报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

VUE使用axios数据请求时报错 TypeError: Cannot set property 'xxxx' of undefined 的解决办法

Vue3 在Axios中添加数据来自于sessionStorage的请求头(请求头添加token)

Vue3 在Axios中添加数据来自于sessionStorage的请求头(请求头添加token)

Vue3 在Axios中添加数据来自于sessionStorage的请求头(请求头添加token)