http.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. //引入axios
  2. import axios from 'axios'
  3. //引入用户信息组件
  4. import { menuStatusStore, userInfoStore } from '@/stores'
  5. import { ElMessage } from 'element-plus';
  6. // import { useRouter } from 'vue-router';
  7. import router from '@/router';
  8. const userInfo = userInfoStore()
  9. const menuStatus = menuStatusStore()
  10. //创建axios实例
  11. //创建基础访问路径
  12. // const base_url = 'http://10.113.248.4:8089/'
  13. //30
  14. const base_url = 'http://43.143.198.30:8089/'
  15. //红朵
  16. // const base_url = 'http://129.211.221.44:8089'
  17. //设置axios 默认访问路径
  18. axios.defaults.baseURL = base_url
  19. //设置超时时间
  20. axios.defaults.timeout = 30000
  21. // 设置头部信息
  22. axios.defaults.headers.common['Content-Type'] = 'application/JSON;charset=UTF-8'
  23. //前端跨域配置
  24. axios.defaults.withCredentials = true;
  25. //设置 使用token的白名单
  26. const whiteList = []
  27. //设置请求前的拦截器
  28. axios.interceptors.request.use(
  29. config => {
  30. //在请求前需要做什么
  31. //如果有token---则放在请求头上
  32. config.headers.Authorization = userInfo.token
  33. ? `Bearer ${userInfo.token}`
  34. : "";
  35. return config
  36. },
  37. error => {
  38. //对错误请求需要做些什么
  39. return Promise.reject(error)
  40. }
  41. )
  42. //添加相应拦截器
  43. axios.interceptors.response.use(
  44. response => {
  45. //对响应中做些什么
  46. if (response.data.code === 401) {
  47. // 重定向到登录页
  48. //登录状态失效
  49. //取到缓存里的登录信息
  50. //---将token 去掉
  51. //出现401 浏览器中还存在缓存 就先提示过期了
  52. //然后清除用户信息缓存--重新登录
  53. if (userInfo.token) {
  54. ElMessage({
  55. message: response.data.msg,
  56. type: 'warning'
  57. })
  58. router.push({ name: 'login' })
  59. menuStatus.saveActiveIndex('6')
  60. }
  61. //清除用户缓存
  62. userInfo.clearUserInfo()
  63. // router.push({ name: 'login' })
  64. //此时报告找不到路径
  65. // Toast.fail(response.data.msg);
  66. // Message.error(response.data.msg);
  67. }
  68. return response
  69. }, error => {
  70. Promise.reject(error)
  71. }
  72. )
  73. //封装请求
  74. export const http = <T>(option: any) => {
  75. return new Promise((resolve, reject) => {
  76. axios({
  77. ...option,
  78. }).then(res => {
  79. //在这里应该机解密下
  80. resolve(res.data)
  81. }).catch(error => {
  82. reject(error)
  83. });
  84. })
  85. }