axios.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import store from '~store'
  4. const service = axios.create({
  5. withCredentials: true,
  6. baseUrl: '/'
  7. })
  8. let reqCount = 0 // 请求计数器
  9. const isServer = typeof window === 'undefined'
  10. service.interceptors.request.use(config => {
  11. // is server render, use ${baseUrl} directly rather than ${proxyUrl}
  12. config.url = config.url || '/'
  13. reqCount++
  14. if (isServer) {
  15. if (config.url.indexOf('/inquiry') === 0) {
  16. config.url = process.env.commonUrl + config.url
  17. } else if (config.url.indexOf('/productsuer') === 0) {
  18. config.url = process.env.materialUrl + config.url
  19. } else if (config.url.indexOf('/messages') === 0) {
  20. config.url = process.env.messageUrl + config.url
  21. } else {
  22. config.url = process.env.baseUrl + config.url
  23. }
  24. // config.headers.cookie = store.state.option.cookies + '; ' + store.state.option.sessionId
  25. // config.headers['User-Agent']
  26. } else {
  27. document.getElementById('loading').setAttribute('class', 'loading in')
  28. }
  29. return config
  30. }, error => {
  31. return Promise.reject(error)
  32. })
  33. service.interceptors.response.use(response => {
  34. const cookies = response.headers['set-cookie']
  35. if (cookies && cookies.length) {
  36. for (let i = 0; i < cookies.length; i++) {
  37. if (cookies[i].indexOf('JSESSIONID') > -1) {
  38. const sessionId = cookies[i]
  39. const first = sessionId.indexOf(';')
  40. const second = sessionId.lastIndexOf(';')
  41. const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
  42. store.commit('option/SET_SESSION_ID', newSessionId)
  43. break
  44. }
  45. }
  46. }
  47. if (--reqCount <= 0 && !isServer) {
  48. document.getElementById('loading').setAttribute('class', 'loading')
  49. }
  50. return response
  51. }, error => {
  52. if (--reqCount <= 0 && !isServer) {
  53. document.getElementById('loading').setAttribute('class', 'loading')
  54. }
  55. return Promise.reject(error)
  56. })
  57. Vue.prototype.$http = service
  58. export default service