一、用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 axios from ‘axios‘ import store from ‘../store‘ import router from ‘../router‘ // 请求列表 const requestList = [] // 取消列表 const CancelToken = axios.CancelToken let sources = {} // axios.defaults.timeout = 10000 axios.defaults.headers.post[‘Content-Type‘] = ‘application/json;charset=UTF-8‘ axios.defaults.baseURL = process.env.BASE_URL axios.interceptors.request.use((config) = > { const request = JSON.stringify(config.url) + JSON.stringify(config.data) config.cancelToken = new CancelToken((cancel) = > { sources[request] = cancel }) if (requestList.includes(request)) { sources[request](‘取消重复请求‘) } else { requestList.push(request) store.dispatch(‘changeGlobalState‘, { loading: true }) } const token = store.getters.userInfo.token if (token) { config.headers.token = token } return config }, function(error) { return Promise.reject(error) }) axios.interceptors.response.use(function(response) { const request = JSON.stringify(response.config.url) + JSON.stringify(response.config.data) requestList.splice(requestList.findIndex(item = > item === request), 1) if (requestList.length === 0) { store.dispatch(‘changeGlobalState‘, { loading: false }) } if (response.data.code === 900401) { window.ELEMENT.Message.error(‘认证失效,请重新登录!‘, 1000) router.push(‘/login‘) } return response }, function(error) { if (axios.isCancel(error)) { requestList.length = 0 store.dispatch(‘changeGlobalState‘, { loading: false }) throw new axios.Cancel(‘cancel request‘) } else { window.ELEMENT.Message.error(‘网络请求失败‘, 1000) } return Promise.reject(error) }) const request = function(url, params, config, method) { return new Promise((resolve, reject) = > { axios[method](url, params, Object.assign({}, config)).then(response = > { resolve(response.data) }, err = > { if (err.Cancel) { console.log(err) } else { reject(err) } }). catch (err = > { reject(err) }) }) } const post = (url, params, config = {}) = > { return request(url, params, config, ‘post‘) } const get = (url, params, config = {}) = > { return request(url, params, config, ‘get‘) } export { sources, post, get }
用法:
import {post} from "@/utils/request";
const res: any = post("/iot/configParam", data);
三、抛出项目所有的请求方法
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); };