http.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //引入axios
  2. import axios from 'axios'
  3. //引入用户信息组件
  4. import { userInfoStore } from '@/stores'
  5. import router from "@/router";
  6. const userInfo = userInfoStore()
  7. //创建axios实例
  8. //创建基础访问路径
  9. const base_url = 'http://10.113.248.3:8086'
  10. //设置axios 默认访问路径
  11. axios.defaults.baseURL = base_url
  12. //设置超时时间
  13. axios.defaults.timeout = 30000
  14. // 设置头部信息
  15. axios.defaults.headers.common['Content-Type'] = 'application/JSON;charset=UTF-8'
  16. //前端跨域配置
  17. axios.defaults.withCredentials = true;
  18. //设置 使用token的白名单
  19. const whiteList = []
  20. //设置请求前的拦截器
  21. axios.interceptors.request.use(
  22. config => {
  23. //在请求前需要做什么
  24. //如果有token---则放在请求头上
  25. config.headers.Authorization = userInfo.token
  26. ? `Bearer ${userInfo.token}`
  27. : "";
  28. return config
  29. },
  30. error => {
  31. //对错误请求需要做些什么
  32. return Promise.reject(error)
  33. }
  34. )
  35. //添加相应拦截器
  36. axios.interceptors.response.use(
  37. response => {
  38. //对响应中做些什么
  39. if (response.data.code === 401) {
  40. // 重定向到登录页
  41. router.replace({
  42. path: "/",
  43. // query: {redirect: router.currentRoute.fullPath}
  44. });
  45. //此时报告找不到路径
  46. // Toast.fail(response.data.msg);
  47. // Message.error(response.data.msg);
  48. }
  49. return response
  50. }, error => {
  51. Promise.reject(error)
  52. }
  53. )
  54. //封装请求
  55. export const http = <T>(option: any) => {
  56. return new Promise((resolve, reject) => {
  57. axios({
  58. ...option,
  59. }).then(res => {
  60. //在这里应该机解密下
  61. resolve(res.data)
  62. }).catch(error => {
  63. reject(error)
  64. });
  65. })
  66. }