一、用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);
二、取消重復請求
// 默認利用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)
});
三、拋出項目所有的請求方法
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); };