axios-nuxt.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import Vue from 'vue'
  2. import Axios from 'axios'
  3. export function axiosHttp(store) {
  4. const service = Axios.create({
  5. withCredentials: true,
  6. baseUrl: '/'
  7. })
  8. service.interceptors.request.use(config => {
  9. if (process.server) {
  10. if (config.url.indexOf('.') === -1) {
  11. config.url = process.env.baseUrl + config.url
  12. }
  13. }
  14. // if (typeof window === 'undefined') {
  15. // config.headers.cookie = store.state.option.cookies + '; ' + store.state.option.sessionId
  16. // // config.headers['User-Agent'] = Vue.$store.state.option.userAgent
  17. // } else {
  18. // console.log(store)
  19. // }
  20. return config
  21. }, error => {
  22. return Promise.reject(error)
  23. })
  24. service.interceptors.response.use(response => {
  25. const cookies = response.headers['set-cookie']
  26. if (cookies && cookies.length) {
  27. for (let i = 0; i < cookies.length; i++) {
  28. if (cookies[i].indexOf('JSESSIONID') > -1) {
  29. const sessionId = cookies[i]
  30. const first = sessionId.indexOf(';')
  31. const second = sessionId.lastIndexOf(';')
  32. const newSessionId = sessionId.replace(sessionId.substring(first, second), '')
  33. store.commit('option/SET_SESSION_ID', newSessionId)
  34. break
  35. }
  36. }
  37. }
  38. return response
  39. }, error => {
  40. return Promise.reject(error)
  41. })
  42. Vue.prototype.$http = service
  43. return service
  44. }
  45. export default function ({ isServer, store, req }) {
  46. axiosHttp(store)
  47. }