api.js 908 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. export default function ({ $axios, redirect, app, store }, inject) {
  2. $axios.onRequest(config => {
  3. if(store.state.token){
  4. config.headers.common['Authorization'] = 'Bearer ' + store.state.token;
  5. }
  6. return config;
  7. });
  8. $axios.setHeader('Content-Type', 'application/json');
  9. $axios.onResponse(response =>{
  10. if(response.status === 401){
  11. this.$router.push('/login');
  12. this.$message({
  13. showClose: true,
  14. message: '未授权,请先登录',
  15. type: 'warning'
  16. });
  17. }
  18. });
  19. // Create a custom axios instance
  20. const api = $axios.create({
  21. // headers: {
  22. // common: {
  23. // Accept: 'text/plain, */*'
  24. // }
  25. // },
  26. baseURL: '/api',
  27. timeout: 10000,
  28. withCredentials: true
  29. });
  30. // Set baseURL to something different
  31. // api.setBaseURL('https://my_api.com')
  32. // Inject to context as $api
  33. inject('api', api)
  34. }