旅游教育出版社-数字教材移动端
QYF-GitLab1
12 小时以前 8e3ee81b6ed824866734b7034604121f370f4201
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/* eslint-disable no-constant-condition */
import axios from "axios";
// import router from "@/router";
import myConfig from "@/assets/js/config";
import toolClass from "@/assets/js/toolClass";
import WeChat from "@/assets/js/weChat/weChat";
// import store from "../../store";
 
// 创建 axios 实例
const service = axios.create({
  baseURL: myConfig.requestCtx,
  timeout: myConfig.requestTimeOut, // 请求超时时间
});
 
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // 在请求发送之前做一些处理
    // if (config.url !== "/api/account/loginByPassword") {
    let token = toolClass.getCookie(myConfig.tokenKey);
    if (token) config.headers.Authorization = `bearer ${token}`;
    // if (!/^https:\/\/|http:\/\//.test(config.url)) {
    //   const token = toolClass.getCookie("token-"+myConfig.appId);
    //   if (token && token !== "undefined") {
    //     // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    //     config.headers.Authorization = token;
    //   }
    //   // else {
    //   //   router.push({ name: "login" });
    //   // }
    // }
    // }
    return config;
  },
  (error) => {
    // 发送失败
    Promise.reject(error);
  }
);
 
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    // dataAxios 是 axios 返回数据中的 data
    const dataAxios = response.data;
    // 这个状态码是和后端约定的
    const { success } = dataAxios;
    if (dataAxios.currentDate) {
      sessionStorage.currentDate = new Date(dataAxios.currentDate).getTime();
    }
    // 根据 code 进行判断
    if (success) {
      return dataAxios.data;
    } else {
      // 提示错误
      console.error(dataAxios.msg);
    }
  },
  (error) => {
    if ((error.message = "Network Error")) {
      let loginCode = WeChat.getUrlInfo("weChatLogin");
      if (loginCode.code) {
        WeChat.login(loginCode.code, (data) => {
          toolClass.setCookie(myConfig.tokenKey, data);
          location.reload();
        });
      } else {
        toolClass.delCookie(myConfig.tokenKey);
        WeChat.getCode("weChatLogin");
      }
    } else {
      if (error.response && error.response.data && error.response.data.error) {
        console.error(error.response.data.error.msg);
      } else {
        console.error("请求发生错误");
      }
    }
    return Promise.reject(error);
  }
);
 
export default service;