| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- import { service } from './service'
- import { config } from './config'
- const { default_headers } = config
- // 设置更长的超时时间,单位为毫秒
- service.defaults.timeout = 60000; // 60 秒
- const request = (option: any) => {
- const { headersType, headers, ...otherOption } = option
- return service({
- ...otherOption,
- headers: {
- 'Content-Type': headersType || default_headers,
- ...headers
- }
- })
- }
- export default {
- get: async <T = any>(option: any) => {
- const res = await request({ method: 'GET', ...option })
- return res.data as unknown as T
- },
- post: async <T = any>(option: any) => {
- const res = await request({ method: 'POST', ...option })
- return res.data as unknown as T
- },
- postOriginal: async (option: any) => {
- const res = await request({ method: 'POST', ...option })
- return res
- },
- delete: async <T = any>(option: any) => {
- const res = await request({ method: 'DELETE', ...option })
- return res.data as unknown as T
- },
- put: async <T = any>(option: any) => {
- const res = await request({ method: 'PUT', ...option })
- return res.data as unknown as T
- },
- download: async <T = any>(option: any) => {
- const res = await request({ method: 'GET', responseType: 'blob', ...option })
- return res as unknown as Promise<T>
- },
- upload: async <T = any>(option: any) => {
- // 为上传请求单独设置更长的超时时间,单位为毫秒
- const uploadTimeout = 120000; // 120 秒
- option.timeout = option.timeout || uploadTimeout;
- // 设置请求头为 multipart/form-data
- option.headersType = 'multipart/form-data';
- // 添加上传进度监听
- option.onUploadProgress = (progressEvent: ProgressEvent) => {
- if (progressEvent.lengthComputable) {
- const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
- console.log(`上传进度: ${percentCompleted}%`);
- // 你可以在这里触发自定义事件,通知组件上传进度
- if (option.onProgress) {
- option.onProgress(percentCompleted);
- }
- }
- };
- const res = await request({ method: 'POST', ...option });
- return res as unknown as Promise<T>;
- }
- }
|