axios.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import axios from 'axios'
  2. export default ({app}, inject) => {
  3. const service = axios.create({
  4. withCredentials: true,
  5. baseURL: '/',
  6. timeout: 5000
  7. })
  8. service.interceptors.request.use(config => {
  9. if (process.server) {
  10. config.url = process.env.baseUrl + 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. }
  14. return config
  15. }, error => {
  16. return Promise.reject(error)
  17. })
  18. service.interceptors.response.use(response => {
  19. const cookies = response.headers['set-cookie']
  20. if (cookies && cookies.length) {
  21. for (let i = 0; i < cookies.length; i++) {
  22. if (cookies[i].indexOf('JSESSIONID') > -1) {
  23. const sessionId = cookies[i]
  24. const first = sessionId.indexOf(';')
  25. const second = sessionId.lastIndexOf(';')
  26. const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
  27. app.store.commit('option/SET_SESSION_ID', newSessionId)
  28. break
  29. }
  30. }
  31. }
  32. return response
  33. }, error => {
  34. return Promise.reject(error)
  35. })
  36. inject('http', service)
  37. }