axios.js 2.5 KB

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