apis.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. export default function ({ $axios, redirect, app, store }, inject) {
  2. // Create a custom axios instance
  3. const apis = $axios.create({
  4. // headers: {
  5. // common: {
  6. // Accept: 'text/plain, */*'
  7. // }
  8. // },
  9. baseURL: '/apis',
  10. timeout: 10000,
  11. withCredentials: true
  12. })
  13. apis.onRequest(config => {
  14. if (store.state.token) {
  15. config.headers.authorization = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJwLnNlZWNvZGVyLmNuIiwic3ViIjoiMTc3NjE3MDgxODEiLCJhdWQiOiJzZWVjLW1vb2MiLCJhdXRoX3RpbWUiOjE2MjI2OTAyMTQsImlhdCI6MTYyMjY5MDIxNCwiZXhwIjoxNjIyNzc2NjE0LCJ1c2VyX2luZm8iOnsicGhvbmUiOiIxNzc2MTcwODE4MSIsImVtYWlsIjoiMTE1ODQ5NDMxOEBxcS5jb20iLCJpZCI6MTM3MiwibmFtZSI6ImxpaGUiLCJyb2xlIjoiU1RVREVOVCJ9fQ.y4dY0BFMvK13W43BZQ3DWSf5ppnq1k4ycFwudp9EKRY"
  16. } else {
  17. delete config.headers.authorization
  18. }
  19. return config
  20. })
  21. apis.setHeader('Content-Type', 'application/json')
  22. apis.onResponse(response => {
  23. if (response.status === 401) {
  24. store.commit('saveToken', null)
  25. store.commit('saveUser', {})
  26. redirect('/unauthorized')
  27. }
  28. })
  29. apis.onError(error => {
  30. if (error.response.status === 401) {
  31. store.commit('saveToken', null)
  32. store.commit('saveUser', {})
  33. redirect('/unauthorized')
  34. }
  35. })
  36. // Inject to context as $apis
  37. inject('apis', apis)
  38. }