Blame view

common/utils/request.js 1.99 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
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
  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}`;
    }
  
    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;