zhangwei
2025-12-29 8edec205baf395715c044a86067505d58455b1c6
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
 
import axios from "axios";
import router from "../router";
import $store from "@/store/index.js";
import { ElMessageBox, ElMessage } from 'element-plus'
// 重置提交数据字符集 api
var baseUrl = process.env.NODE_ENV === "development" ? 'Api' : "https://ycm.51zhengcai.com";
console.log(baseUrl,'baseUrl');
const service = axios.create({
  baseURL: baseUrl, // api 的 process.env.BASE_API
  timeout: 60000, // request timeout 'application/json; charset=utf-8'  'application/x-www-form-urlencoded; charset=UTF-8'
  headers: {
    "Content-Type": "application/json; charset=utf-8",
 
  }
  //withCredentials: true //允许请求携带cookie信息
});
let invalidationMark = true;
//请求设置
export const RESPONSETYPE = {
  ARRAYBUFFER: 'arraybuffer',
  BLOB: 'blob',
  DOCUMENT: 'document',
  JSON: 'json',
  STREAM: 'stream',
  TEXT: 'text',
}
service.interceptors.request.use(
  config => { // 可使用async await 做异步操作
    // 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
    // console.log("config:",config)
    config.data = config.data || {}
    const userToken = $store().token;
    if (config?.custom?.needToken) {
      // 获取用户token
      if (!userToken) {
        ElMessageBox.confirm('请先登录', "提示", {
          confirmButtonText: '确定',
          cancelButtonText: "取消",
          type: 'warning',
          callback: (action) => {
            if (action == "confirm") {
              router.push({ path: "/login" })
 
            }
          },
        })
 
      } else {
        config.headers['Authorization'] = 'Bearer ' + userToken;
      }
    }
    //额外需求
    if (config.custom.methodName == 'user.share' || config.custom.methodName == "pages.getpageconfig" || config.custom.methodName == "goods.goodsList") {
      // const userToken = db.get("userToken");
      config.headers['Authorization'] = 'Bearer ' + userToken ? userToken : '';
    }
 
    return config
  }, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
  })
// 响应设置
service.interceptors.response.use(
  response => {
    const data = response.data
    if (response.statusCode == 200) {
      if (data.data === 14007 || data.data === 14006) {
        
      }
 
    }
    return data === undefined ? {} : data
  },
  error => {
    const responseType = error.config?.responseType;
      const errorData = responseType === RESPONSETYPE.ARRAYBUFFER ? arrayBufferHandler(error.response.data) : error.response?.data;
      const status = error.response?.status
      switch(status) {
        case 500:
        case 501:
        case 502:
        case 503:
          messageHandler('服务暂未启动,请稍等一会儿再试~~', 'error');
          return Promise.reject(Error('服务暂未启动'));
        case 401:
          return permissionHandler();
        default:
          const msg = errorData?.msg || errorData?.errorMsg || '系统内部异常,请联系网站管理员';
          messageHandler(msg, 'error');
          return Promise.reject(errorData);
      }
    // return Promise.reject(error);
  }
);
function messageHandler(msg, type) {
  ElMessage({
    message: msg,
    type: type,
    grouping: true,
    duration: 3000
  });
}
 
function permissionHandler() {
  if (invalidationMark) {
    invalidationMark = false;
    ElMessageBox.alert(
      '你已被登出,可以取消继续留在该页面,或者重新登录',
      '确定登出',
      {
        confirmButtonText: '确定',
        callback: () => {
          router.push({ path: "/login" })
          invalidationMark = true;
        }
      }
    )
  }
}
export default service;