axios.js 1.6 KB

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