"use strict";
import QS from "qs";
import Axios from "axios";
import store from "@/store/index";
import { MessageBox } from "element-ui";
// http request 拦截器
Axios.interceptors.request.use(
  config => {
    // console.log('当前环境变量',process.env.VUE_APP_ENV)
    // console.log('当前环境地址',process.env.VUE_APP_URL)
    config.baseURL = process.env.VUE_APP_URL;
    if (!config["params"]) {
      config["params"] = {};
    }
    config.params["token"] = store.state.user.token;
    config.headers["AUTHORIZATION"] = store.state.user.token;
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);
// 添加响应拦截器
Axios.interceptors.response.use(
  res => {
    // 对响应数据做点什么
    console.log('响应',res)
    switch (res.data.code) {
      case 200:
        return res.data;
      case 402:
        MessageBox.confirm(
          `${res.data.msg},可以取消继续留在该页面,或者重新登录`,
          "确定登出",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          location.reload(); // 为了重新实例化vue-router对象 避免bug
        });
        break;
      case undefined:
        return res;
      default:
        return res.data;
    }
  },
  error => {
    console.log('aaaa')
    // 如果需要通过服务端返回的数据在组件内进行判定,
    // 由于拦截器是reject的错误,并不能在组件中读取err信息,可以改reject为 resolve 并且返回err.response
    // 对响应错误做点什么
    let code = error.response.status; // 获取错误状态码
    let msg = error.response.data.msg; // 获取提示信息
    switch (code) {
      case 401:
        MessageBox.confirm(
          `${msg},可以取消继续留在该页面,或者重新登录`,
          "确定登出",
          {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          location.reload(); // 为了重新实例化vue-router对象 避免bug
        });
        break;
      case undefined:
        return Promise.reject(error);
      default:
        return Promise.reject(error);
    }
  }
);
export default {
  get: option => {
    var options = {
      url: option.url,
      timeout: 10000,
      method: option.method || "get",
      params: option.data || {},
      success: option.succ || function() {},
      error: option.error || function() {}
    };
    return Axios.request(options);
  },
  post: option => {
    var options = {
      url: option.url,
      timeout: 1000000,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
      },
      method: option.method || "post",
      data: option.data,
      success: option.succ || function() {},
      error: option.error || function() {}
    };
    if (option.data && option.typea == 1) {
      options.headers["content-Type"] = "application/json;charset=utf-8";
      options.beforeSend = function(xhr) {
        xhr.setRequestHeader("Test", "testheadervalue");
      };
    } else if (option.data && option.typeb == "excel") {
      options.responseType = "blob";
      options.data = QS.stringify(options.data);
    } else if (option.data && option.typea == 2) {
      options.headers["content-Type"] = "multipart/form-data";
    } else {
      options.data = QS.stringify(options.data);
    }
    return Axios.request(options);
  },
  delete: option => {
    var options = {
      url: option.url,
      timeout: 10000,
      method: option.method || "delete",
      params: option.data || {},
      success: option.succ || function() {},
      error: option.error || function() {}
    };
    return Axios.request(options);
  },
  put: option => {
    var options = {
      url: option.url,
      timeout: 10000,
      headers: {
        "Content-Type": "application/x-www-form-urlencoded; charset=utf-8"
      },
      method: option.method || "PUT",
      params: option.data || {},
      success: option.succ || function() {},
      error: option.error || function() {}
    };
    if (option.data && option.typea == 1) {
      options.headers["content-Type"] = "application/json;charset=utf-8";
      options.data = QS.stringify(options.data);
    }
    return Axios.request(options);
  }
};

vue-axios拦截器的更多相关文章

  1. vue axios拦截器 + 自编写插件 实现全局 loading 效果;

    项目需求:用自定义的 .gif 图标实现全局 loading 效果:为避免在每个页面手动添加,且简单高效的实现,经查阅资料,最终采用了 vue axios拦截器 + 自编写 loading 插件:下面 ...

  2. vue --- axios拦截器+form格式请求体

    在vue2.x中使用CLI生成的模板有很大改变,需要自己手动在main.ts同级目录下新建interceptors.ts interceptors.ts import axios from 'axio ...

  3. vue axios 拦截器

    前言 项目中需要验证登录用户身份是否过期,是否有权限进行操作,所以需要根据后台返回不同的状态码进行判断. 第一次使用拦截器,文章中如有不对的地方还请各位大佬帮忙指正谢谢. 正文 axios的拦截器分为 ...

  4. vue axios拦截器的封装

    // request.js import axios from 'axios' import qs from 'qs' // 创建axios实例 const service = axios.creat ...

  5. vue axios拦截器介绍

    关于axios的拦截器是一个作用非常大,非常好用的东西.分为请求拦截器和响应拦截器两种.我一般把拦截器写在main.js里. 1. 请求拦截器 请求拦截器的作用是在请求发送前进行一些操作,例如在每个请 ...

  6. vue axios拦截器加全局loading

    import axios from 'axios' import util from './util' import {showFullScreenLoading, tryHideFullScreen ...

  7. Vue基于vuex、axios拦截器实现loading效果及axios的安装配置

    准备 利用vue-cli脚手架创建项目 进入项目安装vuex.axios(npm install vuex,npm install axios) axios配置 项目中安装axios模块(npm in ...

  8. vue导航守卫和axios拦截器的区别

    在Vue项目中,有两种用户登录状态判断并处理的情况,分别为:导航守卫和axios拦截器. 一.什么是导航守卫? vue-router 提供的导航守卫主要用来通过跳转或取消的方式守卫导航.(在路由跳转时 ...

  9. Vue2学习小记-给Vue2路由导航钩子和axios拦截器做个封装

    1.写在前面 最近在学习Vue2,遇到有些页面请求数据需要用户登录权限.服务器响应不符预期的问题,但是总不能每个页面都做单独处理吧,于是想到axios提供了拦截器这个好东西,再于是就出现了本文. 2. ...

  10. axios拦截器搭配token使用

    在了解到cookie.session.token的作用后学习token的使用 cookie是随着url将参数发送到后台,安全性最低,并且大小受限,不超过4kb左右,它的数据保存在客户端 session ...

随机推荐

  1. Mac 系统更新怎么忽略

    1.在“终端”命令行中输入以下命令: sudo softwareupdate --ignore “macOS Catalina” 2.按回车键,然后输入管理员密码*,然后再次按回车键,以超级用户权限执 ...

  2. JDBC工具类—如何封装JDBC

    “获得数据库连接”操作,将在以后的增删改查所有功能中都存在,可以封装工具类JDBCUtils.提供获取连接对象的方法,从而达到代码的重复利用. 该工具类提供方法:public static Conne ...

  3. DeepLab系列

    论文: (DeepLabV1)Semantic image segmentation with deep convolutional nets and fully connected CRFs (De ...

  4. ssh断连后,保持Linux后台程序连接

    #### ssh断连后,如何保持Linux后台程序继续运行?ssh断连后,要想运行在Linux服务器中的程序继续运行,就要用到screen技术.- ##### 新建`session` ```shell ...

  5. Atomic原子类

    Atomic原子类 Atomic原子类位于并发包java.util.concurrent下的java.util.concurrent.Atomic中. 1. 原子更新基本类型类 使用原子方式更新基本数 ...

  6. 计算机网络要点---Http

    计算机网络要点---Http 1.工作流程 一次HTTP操作称为一个事务,其工作过程可分为四步: 首先客户机与服务器需要建立 TCP 连接.只要单击某个超级链接,HTTP的工作开始. 建立连接后,客户 ...

  7. 【算法•日更•第五十四期】知识扫盲:什么是operator?

    ▎前言 这个东西和迭代器长的很像,但是比迭代器常见的多. 今天就来浅谈operator. ▎定义 operator是C#.C++和pascal的关键字,它和运算符一起使用,表示一个运算符函数,理解时应 ...

  8. Spring Boot系列(三):Spring Boot整合Mybatis源码解析

    一.Mybatis回顾 1.MyBatis介绍 Mybatis是一个半ORM框架,它使用简单的 XML 或注解用于配置和原始映射,将接口和Java的POJOs(普通的Java 对象)映射成数据库中的记 ...

  9. oracle replace的用法

    表数据里面有些数据是有换行或者特殊字符的,想要去掉,但是几千条记录要一条条改基本不可能. 后来想到了replace这个函数,具体用法如下: update 表1 t set t.列1=replace(( ...

  10. 第5篇 Scrum 冲刺博客

    1.站立会议 照骗 进度 成员 昨日完成任务 今日计划任务 遇到的困难 钟智锋 完成技能 完全重构游戏逻辑代码,并编写调试模块 队友的代码已经和想法相去甚远 庄诗楷 制作了开始游戏的界面 进行了相关的 ...