index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import axios from 'axios'
  2. import util from './util'
  3. import constant from './constant'
  4. import router from '../../router'
  5. axios.defaults.withCredentials = true
  6. // 创建一个 axios 实例
  7. const service = axios.create({
  8. baseURL: constant.BASE_URI,
  9. withCredentials: true,
  10. timeout: 20000 // 请求超时时间
  11. })
  12. // 请求拦截器
  13. service.interceptors.request.use(
  14. config => {
  15. // 在请求发送之前做一些处理
  16. if (!/^https:\/\/|http:\/\//.test(config.url)) {
  17. const token = util.getToken()
  18. console.log(token)
  19. if (token && token !== 'undefined') {
  20. // 让每个请求携带token-- ['Authorization']为自定义key 请根据实际情况自行修改
  21. config.headers.Authorization = 'Bearer' + token
  22. }
  23. }
  24. return config
  25. },
  26. error => {
  27. // 发送失败
  28. console.log(error)
  29. Promise.reject(error)
  30. }
  31. )
  32. // 响应拦截器
  33. service.interceptors.response.use(
  34. response => {
  35. const res = response.data
  36. if (res.statusCode === -401) {
  37. util.removeToken()
  38. router.push({
  39. name: 'mobileLogin'
  40. })
  41. }
  42. return response
  43. },
  44. error => {
  45. return Promise.reject(error)
  46. }
  47. )
  48. export default service