一、用Class方法

  1. import axios from "axios";
  2.  
  3. declare var Promise: any;
  4.  
  5. export class Request {
  6. static _instance: Request;
  7.  
  8. static getInstance() {
  9. // tslint:disable-next-line:no-unused-expression
  10. this._instance || (this._instance = new Request());
  11. return this._instance;
  12. }
  13.  
  14. config: any;
  15.  
  16. constructor() {
  17. axios.interceptors.request.use(config => {
  18. // 处理请求数据,如添加Header信息等,
  19. // 完善url等
  20. let baseUrl = '';
  21. config.url = `${baseUrl}${config.url}`;
  22. return config;
  23. });
  24. axios.interceptors.response.use(
  25. response => {
  26. // 处理返回数据
  27. return response.data;
  28. },
  29. error => {
  30. if (error.response.status === 401) {
  31. // 未登录
  32. } else if (error.response.status === 400) {
  33. // 错误信息 alert
  34. }
  35.  
  36. return Promise.reject(error);
  37. }
  38. );
  39. }
  40.  
  41. get(url: string, config: object = {}) {
  42. return axios.get(url, config);
  43. }
  44.  
  45. post(url: string, data: any = {}, config: object = {}) {
  46. return axios.post(url, data, config);
  47. }
  48.  
  49. put(url: string, data: any, config: object = {}) {
  50. return axios.put(url, data, config);
  51. }
  52.  
  53. delete(url: string, config: object = {}) {
  54. return axios.delete(url, config);
  55. }
  56. }

用法:

  1. import {Request} from "@/utils/request";
  2.  
  3. const request = new Request();
  4. const res: any = request.post("/iot/configParam", data);

二、取消重复请求

// 默认利用axios的cancelToken进行防重复提交。
// 如需允许多个提交同时发出。则需要在请求配置config中增加 neverCancel 属性,并设置为true
import axios from "axios";
// import store from '@/store/index';
// import { getSessionId } from '@/utils/auth';
/* 防止重复提交,利用axios的cancelToken */
let pending: any[] = []; // 声明一个数组用于存储每个ajax请求的取消函数和ajax标识
const CancelToken: any = axios.CancelToken;
const removePending: any = (config: any, f: any) => {
  // 获取请求的url
  const flagUrl = config.url;
  // 判断该请求是否在请求队列中
  if (pending.indexOf(flagUrl) !== -1) {
    // 如果在请求中,并存在f,f即axios提供的取消函数
    if (f) {
      f("取消重复请求"); // 执行取消操作
    } else {
      pending.splice(pending.indexOf(flagUrl), 1); // 把这条记录从数组中移除
    }
  } else {
    // 如果不存在在请求队列中,加入队列
    if (f) {
      pending.push(flagUrl);
    }
  }
};
/* 创建axios实例 */
const service = axios.create({
  timeout: 5000 // 请求超时时间
});
/* request拦截器 */
service.interceptors.request.use(
  (config: any) => {
    // neverCancel 配置项,允许多个请求
    if (!config.neverCancel) {
      // 生成cancelToken
      config.cancelToken = new CancelToken((c: any) => {
        removePending(config, c);
      });
    }
    // 在这里可以统一修改请求头,例如 加入 用户 token 等操作
    //   if (store.getters.sessionId) {
    //     config.headers['X-SessionId'] = getSessionId(); // 让每个请求携带token--['X-Token']为自定义key
    //   }
    return config;
  },
  (error: any) => {
    Promise.reject(error);
  }
);
/* respone拦截器 */
service.interceptors.response.use(
  (response: any) => {
    // console.log(response)
    // 移除队列中的该请求,注意这时候没有传第二个参数f
    removePending(response.config);
    // 获取返回数据,并处理。按自己业务需求修改。下面只是个demo
    const code = response.code !== undefined ? response.code : response.status;
    if (code !== 200) {
      return Promise.reject("error");
    } else {
      return response;
    }
  },
  (error: any) => {
    // 异常处理
    console.log(error);
    pending = [];
    if (error.message === "取消重复请求") {
      return Promise.reject(error);
    }
    return Promise.reject(error);
  }
);
export default service;

用法:

import request from "@/utils/request";

request({
  method: "GET",
  url: "/api/workflow/getAllUserPermission",
  // params: {
  //   test: 6
  // }
}).then((result) = > {
  // console.log(result)
}).
catch ((err) = > {
  // console.log(err)
});

三、抛出项目所有的请求方法

  1. import axios, {
  2. AxiosResponse, AxiosRequestConfig
  3. }
  4. from "axios";
  5. import requestConfig from "@/config/requestConfig";
  6. // import {
  7. // showFullScreenLoading,
  8. // tryHideFullScreenLoading
  9. // } from "./axiosHelperLoading";
  10. // 公共参数
  11. const conmomPrams: object = {};
  12. class HttpRequest {
  13. public queue: any; // 请求的url集合
  14. public constructor() {
  15. this.queue = {};
  16. }
  17. destroy(url: string) {
  18. delete this.queue[url];
  19. // 关闭全局的loading...
  20. if (!Object.keys(this.queue).length) {
  21. // tryHideFullScreenLoading();
  22. }
  23. }
  24. interceptors(instance: any, url ? : string) {
  25. // 请求拦截
  26. instance.interceptors.request.use(
  27. (config: AxiosRequestConfig) = > {
  28. // 在请求前统一添加headers信息
  29. config.headers = {};
  30. // 添加全局的loading...
  31. if (!Object.keys(this.queue).length) {
  32. // showFullScreenLoading();
  33. }
  34. if (url) {
  35. this.queue[url] = true;
  36. }
  37. return config;
  38. }, (error: any) = > {
  39. console.error(error);
  40. });
  41. // 响应拦截
  42. instance.interceptors.response.use(
  43. (res: AxiosResponse) = > {
  44. if (url) {
  45. this.destroy(url);
  46. }
  47. const {
  48. data, status
  49. } = res;
  50. // 请求成功
  51. if (status === 200 && data) {
  52. return data;
  53. }
  54. return requestFail(res);
  55. },
  56. // 失败回调
  57. (error: any) = > {
  58. if (url) {
  59. this.destroy(url);
  60. }
  61. console.error(error);
  62. });
  63. }
  64. async request(options: AxiosRequestConfig) {
  65. const instance = axios.create();
  66. await this.interceptors(instance, options.url);
  67. return instance(options);
  68. }
  69. }
  70. // 请求失败
  71. const requestFail = (res: AxiosResponse) = > {
  72. let errCode = 408;
  73. let errStr = "网络繁忙!";
  74. return {
  75. err: console.error({
  76. code: res.data.code || errCode,
  77. msg: res.data.message || errStr
  78. })
  79. };
  80. };
  81. // 合并axios参数
  82. const conbineOptions = (opts: any): AxiosRequestConfig = > {
  83. const _data = {...conmomPrams, ...opts.data
  84. };
  85. const options = {
  86. method: opts.method || "GET",
  87. url: opts.url,
  88. headers: opts.headers
  89. // baseURL: process.env.VUE_APP_BASE_API,
  90. // timeout: 5000
  91. };
  92. return options.method !== "GET" ? Object.assign(options, {
  93. data: _data
  94. }) : Object.assign(options, {
  95. params: _data
  96. });
  97. };
  98. const HTTP = new HttpRequest();
  99. /**
  100. * 抛出整个项目的api方法
  101. */
  102. const Api = (() = > {
  103. const apiObj: any = {};
  104. const requestList: any = requestConfig;
  105. const fun = (opts: AxiosRequestConfig) = > {
  106. return async(params: any = {}) = > {
  107. Object.assign(opts, params);
  108. const newOpts = conbineOptions(opts);
  109. const res = await HTTP.request(newOpts);
  110. return res;
  111. };
  112. };
  113. Object.keys(requestConfig).forEach(key = > {
  114. let opts = {
  115. url: requestList[key]
  116. };
  117. apiObj[key] = fun(opts);
  118. });
  119. return apiObj;
  120. })();
  121. export
  122. default Api as any;

用法:

  1. import Api from "@/utils/request";
  2.  
  3. export const getKtUploadYxsj = (params = {}) = > {
  4. return Api.getKtUploadYxsj(params);
  5. };

axios二次封装的几种方法的更多相关文章

  1. 原生 Ajax 封装 和 Axios 二次 封装

    AJAX 异步的JavaScript与XML技术( Asynchronous JavaScript and XML ) Ajax 不需要任何浏览器插件,能在不更新整个页面的前提下维护数据,但需要用户允 ...

  2. axios 二次封装

    一般项目往往要对 axios 库进行二次封装,添加一些自定义配置和拦截器等 案例 ./service/axios.js 1234567891011121314151617181920212223242 ...

  3. 【vue】axios二次封装,更好的管理api接口和使用

    在现在的前端开发中,前后端分离开发比较主流,所以在封装方法和模块化上也是非常需要掌握的一门技巧.而axios的封装也是非常的多,下面的封装其实跟百度上搜出来的axios封装或者axios二次封装区别不 ...

  4. PHP生成带logo图像二维码的两种方法

    本文主要和大家分享PHP生成带logo图像二维码的两种方法,主要以文字和代码的形式和大家分享,希望能帮助到大家. 一.利用Google API生成二维码Google提供了较为完善的二维码生成接口,调用 ...

  5. 微信支付支付宝支付生成二维码的方法(php生成二维码的三种方法)

    如果图简单,可以用在线生成 http://pan.baidu.com/share/qrcode?w=150&h=150&url=http://www.xinzhenkj.com 最简单 ...

  6. JS模拟实现封装的三种方法

      前  言  继承是使用一个子类继承另一个父类,那么子类可以自动拥有父类中的所有属性和方法,这个过程叫做继承!  JS中有很多实现继承的方法,今天我给大家介绍其中的三种吧. 1.在 Object类上 ...

  7. [PHP] 生成二维码(两种方法)

    方法一:(调用google二维码接口,本人测试网不好,不好用!) <?php //1.封装生成二维码图片的函数(方法) /** *利用google api生成二维码图片 * $content:二 ...

  8. 使用PHP生成二维码的两种方法(带logo图像)

    一.利用Google API生成二维码 Google提供了较为完善的二维码生成接口,调用API接口很简单,以下是调用代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...

  9. axios二次封装

    import axios from "axios" //请求拦截器 axios.interceptors.request.use(function (config) { retur ...

随机推荐

  1. [Google Guava] 12-数学运算

    原文链接 译文链接 译者:沈义扬 范例 1 int logFloor = LongMath.log2(n, FLOOR); 2 int mustNotOverflow = IntMath.checke ...

  2. 7、组件注册-@Conditional-按照条件注册bean

    7.组件注册-@Conditional-按照条件注册bean @Conditional 按照一定的条件进行判断,满足条件给容器注入bean 按照条件进行动态装配. Spring 4 开始提供的一个注解 ...

  3. Jenkins 自动化构建

    def pipeId = 1130561944231279390 def pipeLogId def isTagOrBranch def tagOrBranch def imageId def add ...

  4. MySQL数据分析-(6)数据库设计之规范化

    大家好,我是jacky,很高兴继续跟大家学习MySQL数据分析这门课,上次课我们介绍了E-R图,我们要给手机销售公司设计数据库,那么同一个项目,10个设计人员可能设计出10种不同的E-R图:因为不同的 ...

  5. 2019PKUWC游记

    有的时候,不是你不会 而是你,认为你不会 ——*Miracle* 本篇游记就简单写了 Day-inf 犹豫许久,还是选择了北大 不是因为喜欢——甚至恰好相反 而是,听说清华高手较多,约型单一, 于是我 ...

  6. spring boot处理跨域

    使用重写WebMvcConfigurer的方式 @Component public class WebMvcConfig extends WebMvcConfigurationSupport { @O ...

  7. csp-s模拟109

    这场考试状态是极差,也因而无畏地打下了三个乱搞.然而这场确实挺乱搞.T1状压但我没优化而选择循环展开,T2打$bitset$随机化(考场上打的有问题不是随机但也能A),T3贪心骗分.但是因为状态实在太 ...

  8. Leetcode题目283.移动零(简单)

    题目描述: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原 ...

  9. vue js select下拉框

    <template> <ul id="select"> <li> <div class="select-head"&g ...

  10. PHP学习之工厂方法模式

    <?php //工厂方法模式 interface Doing { function eat(); function sleep(); } class Cat implements Doing { ...