微信

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