request.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import router from '../router'
  4. import { getCookieValue } from '../utils'
  5. import { platform } from '../utils/platform'
  6. const request = axios.create({
  7. withCredentials: true,
  8. baseURL: process.env.API_DOMAIN,
  9. timeout: 50000,
  10. headers: {
  11. 'Content-Type': 'application/json;charset=UTF-8'
  12. }
  13. })
  14. let tingbangSource = 'h5'
  15. if (platform.isAlipay) {
  16. tingbangSource = 'alipay'
  17. } else if (platform.isWeixin) {
  18. tingbangSource = 'wechat'
  19. }
  20. // Add a request interceptor
  21. request.interceptors.request.use(request => {
  22. request.headers.token = getCookieValue('afhousetoken')
  23. request.headers.tingbangSource = tingbangSource
  24. if (platform.isWeixin) {
  25. request.headers.wechatToken = getCookieValue('afhousewechatToken')
  26. }
  27. return request
  28. }, error => {
  29. // Do something with request error
  30. return Promise.reject(error)
  31. })
  32. // Add a response interceptor
  33. request.interceptors.response.use(response => {
  34. // Do something with response data
  35. const { code, authorizeUrl } = response.data
  36. if (code === 301 && authorizeUrl) {
  37. Vue.cookie.delete('afhousewechatToken')
  38. location.replace(authorizeUrl)
  39. } else if (code === 403) {
  40. router.push('/login')
  41. }
  42. return response.data
  43. }, (error) => {
  44. // Do something with response error
  45. return Promise.reject(error)
  46. })
  47. export default request