微信

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import axios from 'axios'
  2. import qs from 'qs'
  3. import toolClass from './util'
  4. import router from '../pages/user/router'
  5. import { Toast } from '../../node_modules/vant';
  6. const token = function (headers) {
  7. let JWT
  8. if (headers){
  9. localStorage.setItem('JWT', headers.authorization)
  10. JWT = headers.authorization
  11. }
  12. const token = JWT ? JWT : localStorage.getItem('JWT')
  13. return !token ? '' : token
  14. }
  15. const Axios = axios.create({
  16. timeout: 60000,
  17. responseType: 'json',
  18. withCredentials: true,
  19. queryData: {},
  20. urlData: {},
  21. headers: {
  22. 'Content-Type': 'multipart/form-data',
  23. 'authorization': token()
  24. }
  25. })
  26. Axios.interceptors.request.use((config) => {
  27. config.headers.authorization = token()
  28. // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
  29. config.urlData = { ...config.urlData, org: 'MQ' }
  30. let queryData = qs.stringify(config.queryData)
  31. // 判断是通过斜杠传参还是通过query传参
  32. if (config.url.indexOf(':') > -1) {
  33. if (typeof config.urlData === 'object') {
  34. config.url = Object.keys(config.urlData).reduce((url, k) => { // 此方法对每个元素进行处理
  35. const re = new RegExp(`:${k}(?!w)`, 'i')
  36. return url.replace(re, config.urlData[k])
  37. }, config.url)
  38. }
  39. }
  40. if (queryData) {
  41. config.url += '?' + queryData
  42. }
  43. let fm = new FormData()
  44. for (let k in config.data) {
  45. if (Array.isArray(config.data[k])) {
  46. fm.append(k, ...config.data[k].map(v => `${k}=${encodeURIComponent(v)}`))
  47. } else {
  48. fm.append(k, config.data[k])
  49. }
  50. }
  51. config.data = fm
  52. return config
  53. }, (error) => {
  54. console.log(error)
  55. })
  56. const ajax = (...args) => {
  57. return new Promise((resolve, reject) => {
  58. Axios(...args).then(({ data, headers }) => {
  59. if (headers.authorization) {
  60. token(headers)
  61. }
  62. const { code, message, result } = data
  63. if (code === 200) {
  64. resolve(result)
  65. } else if (code === 401) {
  66. // console.log(result)
  67. // reject(code)
  68. toolClass.getCode(result.appid)
  69. } else if (code === 406) {
  70. // console.log(router.history.current.name)
  71. if (router.history.current.name !== 'bindMobile') {
  72. router.push({ name: 'bindMobile' })
  73. }
  74. } else {
  75. // console.log(message)
  76. Toast.fail({
  77. duration: 2000, // 持续展示 toast
  78. forbidClick: true, // 禁用背景点击
  79. message: message
  80. })
  81. reject(message)
  82. }
  83. }).catch(reject)
  84. })
  85. }
  86. export default ajax