axios.js 1.8 KB

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