axios.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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('/cmsApi') === 0) {
  20. config.url = process.env.cmsUrl + config.url
  21. } else {
  22. config.url = process.env.baseUrl + config.url
  23. }
  24. // console.log(config.url)
  25. // config.headers.cookie = store.state.option.cookies + '; ' + store.state.option.sessionId
  26. // config.headers['User-Agent']
  27. } else {
  28. document.getElementById('loading').setAttribute('class', 'loading in')
  29. }
  30. return config
  31. }, error => {
  32. return Promise.reject(error)
  33. })
  34. service.interceptors.response.use(response => {
  35. const cookies = response.headers['set-cookie']
  36. if (cookies && cookies.length) {
  37. for (let i = 0; i < cookies.length; i++) {
  38. if (cookies[i].indexOf('JSESSIONID') > -1) {
  39. const sessionId = cookies[i]
  40. const first = sessionId.indexOf(';')
  41. const second = sessionId.lastIndexOf(';')
  42. const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
  43. store.commit('option/SET_SESSION_ID', newSessionId)
  44. break
  45. }
  46. }
  47. }
  48. if (--reqCount <= 0 && !isServer) {
  49. document.getElementById('loading').setAttribute('class', 'loading')
  50. }
  51. return response
  52. }, error => {
  53. if (--reqCount <= 0 && !isServer) {
  54. document.getElementById('loading').setAttribute('class', 'loading')
  55. }
  56. return Promise.reject(error)
  57. })
  58. Vue.prototype.$http = service
  59. export default service