Blame view

common/utils/request.js 2.33 KB
c293da23   刘淇   新园林init
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  import globalConfig from '@/common/config/global';
  import cache from '@/common/utils/cache';
  import { useUserStore } from '@/pinia/user';
  
  const request = (options) => {
    const defaultOptions = {
      url: '',
      method: 'GET',
      data: {},
      header: { 'Content-Type': 'application/json' },
      timeout: globalConfig.api.timeout
    };
  
    const opts = { ...defaultOptions, ...options };
    let token = '';
    try {
      const userStore = useUserStore();
      token = userStore.token || cache.get(globalConfig.cache.tokenKey);
    } catch (err) {
      token = cache.get(globalConfig.cache.tokenKey);
    }
  
    if (token) {
      opts.header['Authorization'] = `Bearer ${token}`;
50ad810a   王彪总   业务线 小程序不用写死,从后端接口获取
25
26
27
28
    } else if (globalConfig.tenantId) {
      // 多租户:未登录时后端无法从 token 推导租户,必须显式携带 tenant-id(登录、刷新令牌等接口)
      // 已登录请求由后端按 token 取租户,故不硬编码此头,避免将来多租户下跨租户 403
      opts.header['tenant-id'] = String(globalConfig.tenantId);
c293da23   刘淇   新园林init
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
    }
  
    opts.url = globalConfig.api.baseUrl + opts.url;
  
    return new Promise((resolve, reject) => {
      uni.request({
        ...opts,
        success: (res) => {
          if (res.statusCode === 200) {
            const { code, data, msg } = res.data;
            if (code === 0) {
              resolve(data);
            } else if (code === 401) {
              const userStore = useUserStore();
              userStore.logout();
              uni.showToast({ title: msg || '登录过期', icon: 'none' });
              reject(res.data);
            } else {
              uni.showToast({ title: msg || '请求失败', icon: 'none' });
              reject(res.data);
            }
          } else {
            uni.showToast({ title: `错误:${res.statusCode}`, icon: 'none' });
            reject(res);
          }
        },
        fail: (err) => {
          uni.showToast({ title: '网络失败', icon: 'none' });
          reject(err);
        }
      });
    });
  };
  
  export const get = (url, data = {}, options = {}) => request({ url, method: 'GET', data, ...options });
  export const post = (url, data = {}, options = {}) => request({ url, method: 'POST', data, ...options });
  export const put = (url, data = {}, options = {}) => request({ url, method: 'PUT', data, ...options });
  export const del = (url, data = {}, options = {}) => request({ url, method: 'DELETE', data, ...options });
  
  export default request;