解决添加多租户之后的前后端数据错误问题。

This commit is contained in:
zhonghua1
2025-12-17 10:43:03 +08:00
parent 74a5742e03
commit 0467861168
3 changed files with 116 additions and 27 deletions

View File

@@ -10,9 +10,97 @@ interceptorChooseImage()
// #endif // #endif
const db = uniCloud.database() 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() { export default async function() {
const debug = uniStarterConfig.debug; const debug = uniStarterConfig.debug;
// 设置全局请求拦截器(在所有请求之前)
setupRequestInterceptor()
// uniStarterConfig挂载到getApp().globalData.config // uniStarterConfig挂载到getApp().globalData.config
setTimeout(() => { setTimeout(() => {
getApp({ getApp({

View File

@@ -82,16 +82,6 @@ export function request(options = {}) {
if (tenantId) { if (tenantId) {
// 将 tenantId 放入 X-Tenant-Id header适用于所有请求类型GET、POST、PUT、DELETE // 将 tenantId 放入 X-Tenant-Id header适用于所有请求类型GET、POST、PUT、DELETE
requestHeader['X-Tenant-Id'] = tenantId requestHeader['X-Tenant-Id'] = tenantId
// 添加日志,证明已发送 X-Tenant-Id header
console.log('[Request] ✅ 已添加 X-Tenant-Id header:', {
url: finalUrl,
method: method.toUpperCase(),
'X-Tenant-Id': tenantId,
headers: { ...requestHeader }
})
} else {
console.warn('[Request] ⚠️ 未找到 tenantId请求可能失败。请确保已登录并获取到 tenantId')
} }
} }
@@ -105,22 +95,12 @@ export function request(options = {}) {
timeout, timeout,
...restOptions, ...restOptions,
success: (res) => { success: (res) => {
// 请求成功时也输出日志,确认 header 已发送
if (needTenantId && requestHeader['X-Tenant-Id']) {
console.log('[Request] ✅ 请求成功,已发送 X-Tenant-Id:', {
url: finalUrl,
method: method.toUpperCase(),
'X-Tenant-Id': requestHeader['X-Tenant-Id'],
statusCode: res.statusCode
})
}
resolve(res) resolve(res)
}, },
fail: (err) => { fail: (err) => {
console.error('[Request] 请求失败:', { console.error('[Request] 请求失败:', {
url: finalUrl, url: finalUrl,
method: method.toUpperCase(), method: method.toUpperCase(),
'X-Tenant-Id': requestHeader['X-Tenant-Id'] || '未设置',
error: err error: err
}) })
reject(err) reject(err)

View File

@@ -77,7 +77,7 @@
<view <view
class="service-card" class="service-card"
v-for="(item, index) in serviceStatusList" v-for="(item, index) in serviceStatusList"
:key="index" :key="item.id || index"
@click="viewServiceDetail(item)"> @click="viewServiceDetail(item)">
<view class="card-header"> <view class="card-header">
<view class="staff-info"> <view class="staff-info">
@@ -590,14 +590,26 @@ import { getApiUrl } from "@/common/config.js";
method: 'GET', method: 'GET',
timeout: 10000 timeout: 10000
}); });
if (res.statusCode === 200 && res.data && res.data.success) { if (res.statusCode === 200 && res.data && res.data.success) {
const records = Array.isArray(res.data.data) ? res.data.data : []; const records = Array.isArray(res.data.data) ? res.data.data : [];
const mapped = records.map(item => this.buildServiceStatusItem(item));
if (records.length === 0) {
this.serviceStatusList = [];
this.serviceStatusTotal = 0;
return;
}
const mapped = records
.map(item => this.buildServiceStatusItem(item))
.filter(item => item !== null); // 过滤掉无效的数据
// 第一页或强制刷新时重置列表,否则追加 // 第一页或强制刷新时重置列表,否则追加
if (this.serviceStatusPage.current === 1 || force) { if (this.serviceStatusPage.current === 1 || force) {
this.serviceStatusList = mapped; // 使用 Vue 3 的响应式更新方式
this.serviceStatusList = [...mapped];
} else { } else {
this.serviceStatusList = this.serviceStatusList.concat(mapped); this.serviceStatusList = [...this.serviceStatusList, ...mapped];
} }
this.serviceStatusTotal = Number(res.data.total) || 0; this.serviceStatusTotal = Number(res.data.total) || 0;
} else { } else {
@@ -619,6 +631,11 @@ import { getApiUrl } from "@/common/config.js";
} }
}, },
buildServiceStatusItem(record = {}) { buildServiceStatusItem(record = {}) {
if (!record || typeof record !== 'object') {
console.warn('[buildServiceStatusItem] 记录数据无效:', record);
return null;
}
const formattedUpdateTime = this.formatDateTime(record.updateTime || record.createTime); const formattedUpdateTime = this.formatDateTime(record.updateTime || record.createTime);
const tags = []; const tags = [];
if (record.recordingName) { if (record.recordingName) {
@@ -630,8 +647,9 @@ import { getApiUrl } from "@/common/config.js";
if (record.projectName) { if (record.projectName) {
tags.push({ text: `项目:${record.projectName}`, color: 'blue' }); tags.push({ text: `项目:${record.projectName}`, color: 'blue' });
} }
return {
id: record.id, const item = {
id: record.id || '',
staffName: record.salesName || '未分配销售', staffName: record.salesName || '未分配销售',
status: record.syncStatus || '服务中', status: record.syncStatus || '服务中',
customerName: record.customerName || '', customerName: record.customerName || '',
@@ -639,6 +657,9 @@ import { getApiUrl } from "@/common/config.js";
tags, tags,
durationText: formattedUpdateTime ? `最近更新时间:${formattedUpdateTime}` : '最近暂无更新时间' durationText: formattedUpdateTime ? `最近更新时间:${formattedUpdateTime}` : '最近暂无更新时间'
}; };
console.log('[buildServiceStatusItem] 构建的列表项:', item);
return item;
}, },
formatDateTime(value) { formatDateTime(value) {
if (!value) { if (!value) {