1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| import axios from 'axios' import { showMessage } from "./status"; import { saveAs } from 'file-saver'; import { tansParams, blobValidate } from '../index'
const service = axios.create({ baseURL: '', timeout: 16000 })
service.interceptors.request.use( config => { const isNoToken: boolean = ((config.headers || {}) as any).isToken === false if (!isNoToken) { } return config; }, error => { return Promise.reject(error); } );
service.interceptors.response.use( response => { if (response.request.responseType === 'blob' || response.request.responseType === 'arraybuffer') { return response.data } return response.data; }, error => { const { response } = error; if (response) { showMessage(response.status); return Promise.reject(response.data); } else { } } );
export function request(url:string = '', type:string = 'POST', params:any = {},headers: any={}) { return new Promise((resolve, reject) => { let promise if (type.toUpperCase() === 'GET') { promise = service({ url, params, headers }) } else if (type.toUpperCase() === 'POST') { promise = service({ method: 'POST', url, data: params, headers }) } (promise as Promise<any>).then(res => { resolve(res) }).catch(err => { reject(err) }) }) }
export function download(url: string, params: any, filename: string | undefined, config: any) { return service.post(url, params, { transformRequest: [(params) => { return tansParams(params) }], headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, responseType: 'blob', ...config }).then(async (data: any) => { const isLogin = await blobValidate(data); if (isLogin) { const blob = new Blob([data]) saveAs(blob, filename) } else { const resText = await data.text(); const rspObj = JSON.parse(resText); console.error(rspObj) } }).catch((r) => { console.error(r) console.error('下载文件出现错误,请联系管理员!') }) }
|