request.js
4.42 KB
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
/*
* @Date: 2022-09-19 14:11:06
* @LastEditors: hookehuyr hookehuyr@gmail.com
* @LastEditTime: 2026-01-06 21:41:47
* @FilePath: /itomix/git/xyxBooking-weapp/src/utils/request.js
* @Description: 简单axios封装,后续按实际处理
*/
// import axios from 'axios'
import axios from 'axios-miniprogram';
import Taro from '@tarojs/taro'
import qs from 'qs'
import { strExist } from './tools'
import { routerStore } from '@/stores/router'
// import { ProgressStart, ProgressEnd } from '@/components/axios-progress/progress';
// import store from '@/store'
// import { getToken } from '@/utils/auth'
import BASE_URL from './config';
/**
* 获取sessionid的工具函数
* @returns {string|null} sessionid或null
*/
const getSessionId = () => {
try {
return Taro.getStorageSync("sessionid") || null;
} catch (error) {
console.error('获取sessionid失败:', error);
return null;
}
};
const getCurrentPageFullPath = () => {
try {
const pages = Taro.getCurrentPages()
if (!pages || pages.length === 0) return ''
const currentPage = pages[pages.length - 1]
const route = currentPage.route
const options = currentPage.options || {}
const queryParams = Object.keys(options)
.map(key => `${key}=${encodeURIComponent(options[key])}`)
.join('&')
return queryParams ? `${route}?${queryParams}` : route
} catch (error) {
return ''
}
}
const isPlainObject = (value) => {
if (value === null || typeof value !== 'object') return false
return Object.prototype.toString.call(value) === '[object Object]'
}
// create an axios instance
const service = axios.create({
baseURL: BASE_URL, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
timeout: 5000, // request timeout
})
service.defaults.params = {
f: 'reserve',
client_name: '智慧西园寺',
};
// request interceptor
service.interceptors.request.use(
config => {
// console.warn(config)
// console.warn(store)
/**
* 动态获取sessionid并设置到请求头
* 确保每个请求都带上最新的sessionid
*/
const sessionid = getSessionId();
if (sessionid) {
config.headers.cookie = sessionid;
}
// 增加时间戳
if (config.method === 'get') {
config.params = { ...config.params, timestamp: (new Date()).valueOf() }
}
if ((config.method || '').toLowerCase() === 'post') {
const url = config.url || ''
const headers = config.headers || {}
const contentType = headers['content-type'] || headers['Content-Type']
const shouldUrlEncode =
!contentType || String(contentType).includes('application/x-www-form-urlencoded')
if (shouldUrlEncode && !strExist(['upload.qiniup.com'], url) && isPlainObject(config.data)) {
config.headers = {
...headers,
'content-type': 'application/x-www-form-urlencoded'
}
config.data = qs.stringify(config.data)
}
}
return config
},
error => {
// do something with request error
console.error(error, 'err') // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
response => {
const res = response.data
// 401 未授权处理
if (res.code === 401) {
// 跳转到授权页
// 避免死循环,如果已经在 auth 页则不跳
const pages = Taro.getCurrentPages();
const currentPage = pages[pages.length - 1];
if (currentPage && currentPage.route !== 'pages/auth/index') {
const router = routerStore()
const currentPath = getCurrentPageFullPath()
if (currentPath) {
router.add(currentPath)
}
Taro.navigateTo({
url: '/pages/auth/index'
});
}
return response; // 返回 response 以便业务代码处理(或者这里 reject)
}
if (['预约ID不存在'].includes(res.msg)) {
res.show = false;
}
return response
},
error => {
// Taro.showToast({
// title: error.message,
// icon: 'none',
// duration: 2000
// })
return Promise.reject(error)
}
)
export default service