axios.js 2.3 KB

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