axios.js 2.4 KB

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