axios.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. const header = {
  2. }
  3. window.ajaxTimeout = 20000
  4. export default async (
  5. url = '',
  6. data = {},
  7. type = 'GET',
  8. params = {},
  9. headers = header,
  10. onUploadProgress
  11. ) => {
  12. type = type.toLowerCase()
  13. const obj = {
  14. method: type,
  15. baseURL: '',
  16. url: url,
  17. data,
  18. params,
  19. timeout: window.ajaxTimeout,
  20. headers,
  21. onUploadProgress
  22. }
  23. if (onUploadProgress && typeof onUploadProgress === 'function') {
  24. obj.onUploadProgress = onUploadProgress
  25. }
  26. // 请求拦截器
  27. axios.interceptors.request.use(
  28. config => {
  29. return config
  30. },
  31. error => {
  32. // 错误抛到业务代码
  33. return Promise.reject(new Error('服务器异常,请联系管理员!'))
  34. }
  35. )
  36. // 添加响应拦截器
  37. axios.interceptors.response.use(
  38. response => {
  39. return response
  40. },
  41. error => {
  42. return Promise.reject(error.response.data)
  43. }
  44. )
  45. return new Promise((resolve, reject) => {
  46. axios(obj)
  47. .then(response => {
  48. resolve(response.data)
  49. })
  50. .catch(res => {
  51. reject(res)
  52. })
  53. })
  54. }