axios二次封装的几种方法
一、用Class方法
- import axios from "axios";
- declare var Promise: any;
- export class Request {
- static _instance: Request;
- static getInstance() {
- // tslint:disable-next-line:no-unused-expression
- this._instance || (this._instance = new Request());
- return this._instance;
- }
- config: any;
- constructor() {
- axios.interceptors.request.use(config => {
- // 处理请求数据,如添加Header信息等,
- // 完善url等
- let baseUrl = '';
- config.url = `${baseUrl}${config.url}`;
- return config;
- });
- axios.interceptors.response.use(
- response => {
- // 处理返回数据
- return response.data;
- },
- error => {
- if (error.response.status === 401) {
- // 未登录
- } else if (error.response.status === 400) {
- // 错误信息 alert
- }
- return Promise.reject(error);
- }
- );
- }
- get(url: string, config: object = {}) {
- return axios.get(url, config);
- }
- post(url: string, data: any = {}, config: object = {}) {
- return axios.post(url, data, config);
- }
- put(url: string, data: any, config: object = {}) {
- return axios.put(url, data, config);
- }
- delete(url: string, config: object = {}) {
- return axios.delete(url, config);
- }
- }
用法:
- import {Request} from "@/utils/request";
- const request = new Request();
- const res: any = request.post("/iot/configParam", data);
二、取消重复请求
用法:
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)
});
三、抛出项目所有的请求方法
- import axios, {
- AxiosResponse, AxiosRequestConfig
- }
- from "axios";
- import requestConfig from "@/config/requestConfig";
- // import {
- // showFullScreenLoading,
- // tryHideFullScreenLoading
- // } from "./axiosHelperLoading";
- // 公共参数
- const conmomPrams: object = {};
- class HttpRequest {
- public queue: any; // 请求的url集合
- public constructor() {
- this.queue = {};
- }
- destroy(url: string) {
- delete this.queue[url];
- // 关闭全局的loading...
- if (!Object.keys(this.queue).length) {
- // tryHideFullScreenLoading();
- }
- }
- interceptors(instance: any, url ? : string) {
- // 请求拦截
- instance.interceptors.request.use(
- (config: AxiosRequestConfig) = > {
- // 在请求前统一添加headers信息
- config.headers = {};
- // 添加全局的loading...
- if (!Object.keys(this.queue).length) {
- // showFullScreenLoading();
- }
- if (url) {
- this.queue[url] = true;
- }
- return config;
- }, (error: any) = > {
- console.error(error);
- });
- // 响应拦截
- instance.interceptors.response.use(
- (res: AxiosResponse) = > {
- if (url) {
- this.destroy(url);
- }
- const {
- data, status
- } = res;
- // 请求成功
- if (status === 200 && data) {
- return data;
- }
- return requestFail(res);
- },
- // 失败回调
- (error: any) = > {
- if (url) {
- this.destroy(url);
- }
- console.error(error);
- });
- }
- async request(options: AxiosRequestConfig) {
- const instance = axios.create();
- await this.interceptors(instance, options.url);
- return instance(options);
- }
- }
- // 请求失败
- const requestFail = (res: AxiosResponse) = > {
- let errCode = 408;
- let errStr = "网络繁忙!";
- return {
- err: console.error({
- code: res.data.code || errCode,
- msg: res.data.message || errStr
- })
- };
- };
- // 合并axios参数
- const conbineOptions = (opts: any): AxiosRequestConfig = > {
- const _data = {...conmomPrams, ...opts.data
- };
- const options = {
- method: opts.method || "GET",
- url: opts.url,
- headers: opts.headers
- // baseURL: process.env.VUE_APP_BASE_API,
- // timeout: 5000
- };
- return options.method !== "GET" ? Object.assign(options, {
- data: _data
- }) : Object.assign(options, {
- params: _data
- });
- };
- const HTTP = new HttpRequest();
- /**
- * 抛出整个项目的api方法
- */
- const Api = (() = > {
- const apiObj: any = {};
- const requestList: any = requestConfig;
- const fun = (opts: AxiosRequestConfig) = > {
- return async(params: any = {}) = > {
- Object.assign(opts, params);
- const newOpts = conbineOptions(opts);
- const res = await HTTP.request(newOpts);
- return res;
- };
- };
- Object.keys(requestConfig).forEach(key = > {
- let opts = {
- url: requestList[key]
- };
- apiObj[key] = fun(opts);
- });
- return apiObj;
- })();
- export
- default Api as any;
用法:
- import Api from "@/utils/request";
- export const getKtUploadYxsj = (params = {}) = > {
- return Api.getKtUploadYxsj(params);
- };
axios二次封装的几种方法的更多相关文章
- 原生 Ajax 封装 和 Axios 二次 封装
AJAX 异步的JavaScript与XML技术( Asynchronous JavaScript and XML ) Ajax 不需要任何浏览器插件,能在不更新整个页面的前提下维护数据,但需要用户允 ...
- axios 二次封装
一般项目往往要对 axios 库进行二次封装,添加一些自定义配置和拦截器等 案例 ./service/axios.js 1234567891011121314151617181920212223242 ...
- 【vue】axios二次封装,更好的管理api接口和使用
在现在的前端开发中,前后端分离开发比较主流,所以在封装方法和模块化上也是非常需要掌握的一门技巧.而axios的封装也是非常的多,下面的封装其实跟百度上搜出来的axios封装或者axios二次封装区别不 ...
- PHP生成带logo图像二维码的两种方法
本文主要和大家分享PHP生成带logo图像二维码的两种方法,主要以文字和代码的形式和大家分享,希望能帮助到大家. 一.利用Google API生成二维码Google提供了较为完善的二维码生成接口,调用 ...
- 微信支付支付宝支付生成二维码的方法(php生成二维码的三种方法)
如果图简单,可以用在线生成 http://pan.baidu.com/share/qrcode?w=150&h=150&url=http://www.xinzhenkj.com 最简单 ...
- JS模拟实现封装的三种方法
前 言 继承是使用一个子类继承另一个父类,那么子类可以自动拥有父类中的所有属性和方法,这个过程叫做继承! JS中有很多实现继承的方法,今天我给大家介绍其中的三种吧. 1.在 Object类上 ...
- [PHP] 生成二维码(两种方法)
方法一:(调用google二维码接口,本人测试网不好,不好用!) <?php //1.封装生成二维码图片的函数(方法) /** *利用google api生成二维码图片 * $content:二 ...
- 使用PHP生成二维码的两种方法(带logo图像)
一.利用Google API生成二维码 Google提供了较为完善的二维码生成接口,调用API接口很简单,以下是调用代码: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...
- axios二次封装
import axios from "axios" //请求拦截器 axios.interceptors.request.use(function (config) { retur ...
随机推荐
- [Google Guava] 12-数学运算
原文链接 译文链接 译者:沈义扬 范例 1 int logFloor = LongMath.log2(n, FLOOR); 2 int mustNotOverflow = IntMath.checke ...
- 7、组件注册-@Conditional-按照条件注册bean
7.组件注册-@Conditional-按照条件注册bean @Conditional 按照一定的条件进行判断,满足条件给容器注入bean 按照条件进行动态装配. Spring 4 开始提供的一个注解 ...
- Jenkins 自动化构建
def pipeId = 1130561944231279390 def pipeLogId def isTagOrBranch def tagOrBranch def imageId def add ...
- MySQL数据分析-(6)数据库设计之规范化
大家好,我是jacky,很高兴继续跟大家学习MySQL数据分析这门课,上次课我们介绍了E-R图,我们要给手机销售公司设计数据库,那么同一个项目,10个设计人员可能设计出10种不同的E-R图:因为不同的 ...
- 2019PKUWC游记
有的时候,不是你不会 而是你,认为你不会 ——*Miracle* 本篇游记就简单写了 Day-inf 犹豫许久,还是选择了北大 不是因为喜欢——甚至恰好相反 而是,听说清华高手较多,约型单一, 于是我 ...
- spring boot处理跨域
使用重写WebMvcConfigurer的方式 @Component public class WebMvcConfig extends WebMvcConfigurationSupport { @O ...
- csp-s模拟109
这场考试状态是极差,也因而无畏地打下了三个乱搞.然而这场确实挺乱搞.T1状压但我没优化而选择循环展开,T2打$bitset$随机化(考场上打的有问题不是随机但也能A),T3贪心骗分.但是因为状态实在太 ...
- Leetcode题目283.移动零(简单)
题目描述: 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序. 示例: 输入: [0,1,0,3,12] 输出: [1,3,12,0,0] 说明: 必须在原 ...
- vue js select下拉框
<template> <ul id="select"> <li> <div class="select-head"&g ...
- PHP学习之工厂方法模式
<?php //工厂方法模式 interface Doing { function eat(); function sleep(); } class Cat implements Doing { ...