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

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

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

问题:

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

请注意:

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

【问题讨论】:

    标签: vue.js axios vuex vue-router


    【解决方案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');
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-28
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    相关资源
    最近更新 更多