axios.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // import axios from 'axios'
  2. import Router from '@/router/index'
  3. // import store from '@/store'
  4. import urlConfig from '@/apis/url-config'
  5. import {
  6. getToken, removeMenu,
  7. removeBtn, removeToken
  8. } from '@/utils/auth'
  9. const header = {
  10. // "X-Requested-With": "XMLHttpRequest",
  11. // "X-Frame-Options": "DENY", // 告诉浏览器不要(DENY)把这个网页放在iFrame内,通常的目的就是要帮助用户对抗点击劫持。
  12. // "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  13. }
  14. window.ajaxTimeout = 20000
  15. export default async (
  16. url = '',
  17. data = {},
  18. type = 'GET',
  19. params = {},
  20. headers = header,
  21. onUploadProgress
  22. ) => {
  23. type = type.toLowerCase()
  24. console.log(headers)
  25. const obj = {
  26. method: type,
  27. baseURL: '',
  28. url: urlConfig.baseURL + url,
  29. data,
  30. params,
  31. // // `onUploadProgress` 允许为上传处理进度事件
  32. // onUploadProgress: function(progressEvent) {
  33. // // 对原生进度事件的处理
  34. // },
  35. // // `onDownloadProgress` 允许为下载处理进度事件
  36. // onDownloadProgress: function(progressEvent) {
  37. // // 对原生进度事件的处理
  38. // },
  39. // `cancelToken` 指定用于取消请求的 cancel token
  40. // (查看后面的 Cancellation 这节了解更多)
  41. // cancelToken: new CancelToken(function (cancel) {
  42. // }),
  43. processData: true, // 告诉axios不要去处理发送的数据(重要参数)
  44. timeout: window.ajaxTimeout,
  45. headers,
  46. onUploadProgress
  47. }
  48. if (onUploadProgress && typeof onUploadProgress === 'function') {
  49. obj.onUploadProgress = onUploadProgress
  50. }
  51. // return await axios(obj)
  52. // .then(response => {
  53. // return response;
  54. // })
  55. // .catch(res => {
  56. // return res;
  57. // });
  58. // 请求拦截器
  59. axios.interceptors.request.use(
  60. config => {
  61. if (!config.data.token) {
  62. config.data.token = getToken()
  63. }
  64. return config
  65. },
  66. error => {
  67. // 错误抛到业务代码
  68. return Promise.reject(new Error('服务器异常,请联系管理员!'))
  69. }
  70. )
  71. // 添加响应拦截器
  72. axios.interceptors.response.use(
  73. async response => {
  74. if (response.status === 200) {
  75. const code = response.data.code
  76. if (code >= 100 && code <= 104) {
  77. removeToken()
  78. removeMenu()
  79. removeBtn()
  80. }
  81. }
  82. return response
  83. },
  84. error => {
  85. return Promise.reject(error.response.data)
  86. }
  87. )
  88. return new Promise((resolve, reject) => {
  89. axios(obj)
  90. .then(response => {
  91. resolve(response.data)
  92. })
  93. .catch(res => {
  94. if (res.response && res.response.data) {
  95. reject(res.response.data);
  96. } else {
  97. reject(res);
  98. }
  99. });
  100. })
  101. }