city-service.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import axios from 'axios'
  2. export default ({app}, inject) => {
  3. const service = axios.create({
  4. withCredentials: true,
  5. baseURL: '/'
  6. })
  7. service.interceptors.request.use(config => {
  8. // is server render, use ${baseUrl} directly rather than ${proxyUrl}
  9. if (typeof window === 'undefined') {
  10. config.url = process.env.baseUrl + '/city/' + process.env.cityDomain + config.url
  11. config.headers.cookie = app.store.state.option.cookies + '; ' + app.store.state.option.sessionId
  12. config.headers['User-Agent'] = app.store.state.option.userAgent
  13. } else {
  14. config.url = '/city/' + process.env.cityDomain + config.url
  15. }
  16. return config
  17. }, error => {
  18. return Promise.reject(error)
  19. })
  20. service.interceptors.response.use(response => {
  21. const cookies = response.headers['set-cookie']
  22. if (cookies && cookies.length) {
  23. for (let i = 0; i < cookies.length; i++) {
  24. if (cookies[i].indexOf('JSESSIONID') > -1) {
  25. const sessionId = cookies[i]
  26. const first = sessionId.indexOf(';')
  27. const second = sessionId.lastIndexOf(';')
  28. const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
  29. app.store.commit('option/SET_SESSION_ID', newSessionId)
  30. break
  31. }
  32. }
  33. }
  34. return response
  35. }, error => {
  36. return Promise.reject(error)
  37. })
  38. inject('cityService', service)
  39. }