解决添加多租户之后的前后端数据错误问题。
This commit is contained in:
@@ -10,9 +10,97 @@ interceptorChooseImage()
|
||||
|
||||
// #endif
|
||||
const db = uniCloud.database()
|
||||
|
||||
/**
|
||||
* 设置全局 uni.request 拦截器,自动添加 X-Tenant-Id header
|
||||
*/
|
||||
function setupRequestInterceptor() {
|
||||
// 保存原始的 uni.request
|
||||
const originalRequest = uni.request
|
||||
|
||||
// 重写 uni.request,自动添加 tenantId
|
||||
uni.request = function(options = {}) {
|
||||
const { url, header = {}, method = 'GET', ...restOptions } = options
|
||||
|
||||
// 获取 tenantId
|
||||
let tenantId = ''
|
||||
try {
|
||||
tenantId = uni.getStorageSync('backend-tenant-id') || ''
|
||||
} catch (e) {
|
||||
console.error('获取 tenantId 失败:', e)
|
||||
}
|
||||
|
||||
// 构建新的 header(保留原有的 header,避免覆盖)
|
||||
const newHeader = {
|
||||
'Content-Type': 'application/json',
|
||||
...header
|
||||
}
|
||||
|
||||
// 添加 X-Tenant-Id header(如果存在 tenantId)
|
||||
if (tenantId) {
|
||||
newHeader['X-Tenant-Id'] = tenantId
|
||||
}
|
||||
|
||||
// 添加 token(如果存在且未设置)
|
||||
if (!newHeader['Authorization']) {
|
||||
try {
|
||||
const token = uni.getStorageSync('backend-token') || ''
|
||||
if (token) {
|
||||
newHeader['Authorization'] = `Bearer ${token}`
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('获取 token 失败:', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 统一使用 Promise 方式,确保正确返回响应
|
||||
// 这样无论调用方使用 await 还是回调,都能正常工作
|
||||
return new Promise((resolve, reject) => {
|
||||
originalRequest.call(uni, {
|
||||
...restOptions,
|
||||
url,
|
||||
method,
|
||||
header: newHeader,
|
||||
success: (res) => {
|
||||
// 如果提供了 success 回调,先执行它
|
||||
if (options.success) {
|
||||
options.success(res)
|
||||
}
|
||||
// 然后 resolve Promise(供 await 使用)
|
||||
resolve(res)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('[Request Interceptor] 请求失败:', {
|
||||
url: url,
|
||||
method: method.toUpperCase(),
|
||||
error: err
|
||||
})
|
||||
// 如果提供了 fail 回调,先执行它
|
||||
if (options.fail) {
|
||||
options.fail(err)
|
||||
}
|
||||
// 然后 reject Promise(供 await 使用)
|
||||
reject(err)
|
||||
},
|
||||
complete: (res) => {
|
||||
// 如果提供了 complete 回调,执行它
|
||||
if (options.complete) {
|
||||
options.complete(res)
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// 全局请求拦截器已设置,所有 uni.request 调用将自动添加 X-Tenant-Id header
|
||||
}
|
||||
|
||||
export default async function() {
|
||||
const debug = uniStarterConfig.debug;
|
||||
|
||||
// 设置全局请求拦截器(在所有请求之前)
|
||||
setupRequestInterceptor()
|
||||
|
||||
// uniStarterConfig挂载到getApp().globalData.config
|
||||
setTimeout(() => {
|
||||
getApp({
|
||||
|
||||
Reference in New Issue
Block a user