request.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import qs from 'qs'
  2. import axios from 'axios'
  3. import { Toast } from 'vant'
  4. import cleanDeep from 'clean-deep'
  5. import { sessionStorage as storage } from 'js-storage'
  6. import setLoading from '@/utils/loading'
  7. const instance = axios.create({
  8. baseURL: '/api-teacher'
  9. })
  10. instance.interceptors.request.use(config => {
  11. if (config.hideLoading !== true) {
  12. setLoading(true)
  13. }
  14. config.data = cleanDeep(config.data)
  15. config.params = cleanDeep(config.params)
  16. if (config.method.toLocaleUpperCase() === 'POST' && config.requestType === 'form') {
  17. config.data = qs.stringify(config.data)
  18. }
  19. const Authorization = storage.get('token') || localStorage.getItem('Authorization') || localStorage.getItem('userInfo')
  20. if (config.baseURL !== '/api-auth' && Authorization) {
  21. config.headers = {
  22. ...config.headers,
  23. Authorization,
  24. }
  25. }
  26. const tenantId = sessionStorage.getItem('tenantId')
  27. if(tenantId && tenantId != 'undefined') {
  28. config.headers['tenantId'] = tenantId
  29. }
  30. return config
  31. })
  32. instance.interceptors.response.use(res => {
  33. if (res.config.hideLoading !== true) {
  34. setLoading(false)
  35. }
  36. if (!(res.status > 200 || res.status < 200)) {
  37. if (res.data.code === 200) {
  38. return res.data
  39. } else if(res.data.code == 100 || res.data.code == 201) { // 支付时会用到的自定交code
  40. return res.data
  41. } else {
  42. if (res.config.hint !== true) {
  43. Toast(res.data.msg || '接口返回错误')
  44. }
  45. return Promise.reject(res.data)
  46. }
  47. } else {
  48. if (res.config.hint !== true) {
  49. Toast(res.data.msg || '接口返回错误')
  50. }
  51. return Promise.reject('网络错误')
  52. }
  53. }, () => {
  54. setLoading(false)
  55. })
  56. export default instance