axios.js 1.9 KB

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