index.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { service } from './service'
  2. import { config } from './config'
  3. const { default_headers } = config
  4. // 设置更长的超时时间,单位为毫秒
  5. service.defaults.timeout = 60000; // 60 秒
  6. const request = (option: any) => {
  7. const { headersType, headers, ...otherOption } = option
  8. return service({
  9. ...otherOption,
  10. headers: {
  11. 'Content-Type': headersType || default_headers,
  12. ...headers
  13. }
  14. })
  15. }
  16. export default {
  17. get: async <T = any>(option: any) => {
  18. const res = await request({ method: 'GET', ...option })
  19. return res.data as unknown as T
  20. },
  21. post: async <T = any>(option: any) => {
  22. const res = await request({ method: 'POST', ...option })
  23. return res.data as unknown as T
  24. },
  25. postOriginal: async (option: any) => {
  26. const res = await request({ method: 'POST', ...option })
  27. return res
  28. },
  29. delete: async <T = any>(option: any) => {
  30. const res = await request({ method: 'DELETE', ...option })
  31. return res.data as unknown as T
  32. },
  33. put: async <T = any>(option: any) => {
  34. const res = await request({ method: 'PUT', ...option })
  35. return res.data as unknown as T
  36. },
  37. download: async <T = any>(option: any) => {
  38. const res = await request({ method: 'GET', responseType: 'blob', ...option })
  39. return res as unknown as Promise<T>
  40. },
  41. upload: async <T = any>(option: any) => {
  42. // 为上传请求单独设置更长的超时时间,单位为毫秒
  43. const uploadTimeout = 120000; // 120 秒
  44. option.timeout = option.timeout || uploadTimeout;
  45. // 设置请求头为 multipart/form-data
  46. option.headersType = 'multipart/form-data';
  47. // 添加上传进度监听
  48. option.onUploadProgress = (progressEvent: ProgressEvent) => {
  49. if (progressEvent.lengthComputable) {
  50. const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  51. console.log(`上传进度: ${percentCompleted}%`);
  52. // 你可以在这里触发自定义事件,通知组件上传进度
  53. if (option.onProgress) {
  54. option.onProgress(percentCompleted);
  55. }
  56. }
  57. };
  58. const res = await request({ method: 'POST', ...option });
  59. return res as unknown as Promise<T>;
  60. }
  61. }