axios二次封装

查看代码


import axiox from 'axios'
import store from "@/store";
import utils from "@/utils";
import Qs from 'qs'
import {
  Message
} from "element-ui";

const axiosConfig = {
  headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  },

  timeout: 10000,

  // responseType: 'json',
  maxContentLength: 2000,
}

const request = axiox.create(axiosConfig)

let isRefreshing = false
let queue = []

let runQueue = () => {
  isRefreshing = true
  let first = queue.shift()
  first.request()
}

request.interceptors.request.use((config) => {
  const token = utils.storage.get("token");
  if (config.headerType) {
    config.headers['Content-Type'] = config.headerType
  }
  if (config.url.indexOf("api/scrm-system/v1/auth/one_click_login")>-1) {
    //一键登录
    utils.cookie.setCookie("zh-auth", JSON.parse(localStorage.getItem("onelogin")));
    config.headers["zh-auth"] = ${localStorage.getItem("onelogin")};
  } else {
    if (token && !config.clearToken) {
      config.headers["zh-auth"] = ${token};
      config.headers["trace-id"] = utils.storage.get("traceId");
    }

  }

  //自定义表头
  if (config.customHeader) {
    config.headers = {
      ...config.headers,
      ...config.headerObj
    }
  }
  return config;
}, function (error) {
  return Promise.reject(error);
});

request.interceptors.response.use(function (response) {
  if ((response.config ?.url || "").indexOf("api/scrm-system/v1/auth/create_status") > -1||(response.config ?.url || "").indexOf("api/scrm-system/v1/auth/wx_scancode_Login") > -1||(response.config ?.url || "").indexOf("api/scrm-system/v1/auth/one_click_login") > -1) {
    utils.storage.set("token", response.headers["zh-auth"]);
    utils.storage.set("traceId", response.headers["trace-id"]);
    utils.cookie.setCookie("zh-auth", response.headers["zh-auth"]);
  }
  store.dispatch("SetLoding", false);
  isRefreshing = false
  if (!(queue.length === 0)) runQueue()
  if (response.status == 200 && (response.config ?.url || "").indexOf("api/scrm-system/v1/auth/delete_status") > -1 || response.status == "200" && (response.config ?.url || "").indexOf("api/scrm-system/v1/auth/delete_status") > -1||response.status == 401||response.status == "401") {
    utils.cookie.delCookie("tokzh-authen");
    utils.storage.remove("token");
    utils.storage.remove("traceId");
    utils.storage.remove("userInfo");
    Message({
      type: "success",
      message: "已退出登录!",
    });

    window.setTimeout(() => {
        // 手动更新, 刷新权限
    location.reload();
    }, 1000);

  }
  if (response.data) {
    console.log(response, "response.data");
    let result = null;
    if (response.data.code == 100000 || response.data.code == "100000" || response.data.errno == "0") {
      result = {
        ...response.data
      }
    } else {
      Message.error(response.data.msg || response.data.errmsg || "接口报错");
    }

    return result
  }
}, function (error) {
  store.dispatch("SetLoding", false);
  isRefreshing = false
  if (!(queue.length === 0)) runQueue()
  return Promise.reject(error);
});

const httpPost = async ({
  url,
  method = 'POST',
  data = {},
  params = {},
  clearToken = false,
  customHeader = false,
  headerObj = {},
  onUploadProgress = () => {},
  headerType = "",
}) => {
  return new Promise((resolve, reject) => {
    if (!data.noLoading) store.dispatch("SetLoding", true);
    console.log(data, "data");
    let _fun=null;
    if (method=="GET"||method=="DELETE") {
      _fun=(params)=>{
        return Qs.stringify(params, { arrayFormat: 'repeat' })
      }
    }
    queue.push({
      request: () => {
        request({
          method,
          url,
          data,
          params,
          clearToken,
          customHeader,
          headerObj,
          onUploadProgress,
          headerType,
          paramsSerializer:_fun
        }).then(res => {
          resolve(res)
        }).catch(e => {
          reject(e)
        })
      }
    })
    if (!isRefreshing) runQueue()
  })
}

export {
  httpPost
}

Original: https://www.cnblogs.com/wxchun/p/16161131.html
Author: 春春&
Title: axios二次封装

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/586323/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • java入门基础 static final 关键字 修饰符 解释(通俗易懂)

    final 和 static和 final static 区别解释? static是用来修饰静态资源的(包括类、方法、变量等),final 是用来保证当前变量为常量,final s…

    Java 2023年6月7日
    086
  • 详解apollo的设计与使用

    apollo 是一款由携程团队开发的配置中心,可以实现配置的集中管理、分环境管理、即时生效等等。在这篇博客中,我们可以了解到: 这里我回答的是为什么使用配置中心,而不是为什么使用 …

    Java 2023年6月14日
    0106
  • Java面试题(八)–Spring

    1 基础知识 1、说说你对Spring的理解? 1、Spring是一个开源框架,主要是为简化企业级应用开发而生。可以实现EJB可以实现的功能,Spring是一个IOC和AOP容器框…

    Java 2023年6月9日
    081
  • Spring事务提交之后做些操作

    在使用spring事务时,我们通常会把事务内的所有操作当成是一个原子操作。也就是当整个事务内的所有代码都执行完成后, 才会将所有的数据落实到数据库中。这样做有时也会给我们造成麻烦。…

    Java 2023年5月30日
    065
  • Jmix 中 REST API 的两种实现

    你知道吗,在 Jmix 中,REST API 有两种实现方式! 很多应用是采取前后端分离的方式进行开发。这种模式下,对前端的选择相对灵活,可以根据团队的擅长技能选择流行的 Angu…

    Java 2023年6月15日
    075
  • 11、SpringBoot 启动 刷新应用上下文 自动装配解析(三)

    目录:Springboot源码学习目录上文:10、SpringBoot 启动 刷新应用上下文 自动装配解析(二)前言: 配置类解析核心类关系图 配置类的解析其实是Spring的重点…

    Java 2023年6月13日
    072
  • Java 8中Collectors.toMap空指针异常源码分析

    当需要将一个List转换为Map时,可以使用 Java 8 中的 Collectors.toMap() 方法,Map是由key-value组成的键值对集合,在使用 Collecto…

    Java 2023年6月8日
    081
  • Java 知识点

    博客园 :当前访问的博文已被密码保护 请输入阅读密码: Original: https://www.cnblogs.com/linguoguo/p/16050987.htmlAut…

    Java 2023年5月29日
    061
  • Dubbo与SpringBoot整合

    1.选择ZooKeeper作为注册中心 在linux环境中使用docker安装ZooKeeper //拉取zookeeper镜像 docker pull zookeeper//启动…

    Java 2023年6月9日
    071
  • 华为交换机–项目二

    知识点 对于vlan的理解和静态路由的配置,并熟悉 交换机配置的各种常用命令。能对虚拟局域网配置是否正确进行测试 实验要求 按照下面的网络模型图,进行VLAN的配置。 计算机 PC…

    Java 2023年6月15日
    088
  • 0、编程入门

    0、编程入门 1、概述 计算机包括硬件和软件两部分。 硬件:可看见的物理部分; 软件:看不见的指令。 程序设计 定义:开发软件。 应用场景:淘宝、京东等软件。 程序设计语言 帮助开…

    Java 2023年6月13日
    071
  • java多线程回顾2:生命周期与控制

    1、 线程生命周期概述 线程的生命周期如下图: 2、 新建与就绪 当程序使用new关键字创建一个线程之后,线程就处于新建状态了。此时线程只是被分配了内存资源,初始化了成员变量。 当…

    Java 2023年6月15日
    0105
  • Leetcode随缘刷题之寻找两个正序数组的中位数

    我一上来没读清题,想着这题这么简单,直接就上手写了: package leetcode.day_12_05; import java.util.ArrayList; import …

    Java 2023年6月7日
    070
  • Swagger 3.0 天天刷屏,真的香吗?

    前言 官方文档如何说? Spring Boot版本说明 添加依赖 springfox-boot-starter做了什么? 撸起袖子就是干? 定制一个基本的文档示例 文档如何分组? …

    Java 2023年6月14日
    070
  • Java面试整理(精简版)

    特征(OOP) 解释说明 通俗理解 关系联系 作用 封装 隐藏内部细节,只对外暴露访问方法 属性/方法封装,便于使用,限制不合理操作 类-类 低耦合,高内聚,增强代码可维护性;**…

    Java 2023年6月5日
    062
  • SpringMVC请求流程源码分析

    一、SpringMVC使用 1.工程创建 创建maven工程。 添加java、resources目录。 引入Spring-webmvc 依赖。 org.springframewor…

    Java 2023年6月13日
    091
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球