axios.js 2.3 KB

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