feat: 环境的配置

This commit is contained in:
2025-09-15 19:01:22 +08:00
parent 843d8d3138
commit 1038dd3180
9 changed files with 103 additions and 98 deletions

View File

@@ -3,11 +3,5 @@ NODE_ENV = development
# 测试
VITE_BASE_URL = https://onefeel.brother7.cn/ingress
# 生产
# VITE_BASE_URL = https://biz.nianxx.cn
# 测试
VITE_WSS_URL = wss://onefeel.brother7.cn/ingress/agent/ws/chat
# 生产
# VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat

View File

@@ -1,13 +1,7 @@
NODE_ENV = production
# 测试
VITE_BASE_URL = https://onefeel.brother7.cn/ingress
# 生产
VITE_BASE_URL = https://biz.nianxx.cn
# 生产
# VITE_BASE_URL = https://biz.nianxx.cn
# 测试
VITE_WSS_URL = wss://onefeel.brother7.cn/ingress/agent/ws/chat
# 生产
# VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat
VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat

View File

@@ -1,13 +1,7 @@
NODE_ENV = staging
# 测试
VITE_BASE_URL = https://onefeel.brother7.cn/ingress
# 生产
VITE_BASE_URL = https://biz.nianxx.cn
# 生产
# VITE_BASE_URL = https://biz.nianxx.cn
# 测试
VITE_WSS_URL = wss://onefeel.brother7.cn/ingress/agent/ws/chat
# 生产
# VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat
VITE_WSS_URL = wss://biz.nianxx.cn/agent/ws/chat

View File

@@ -1,8 +0,0 @@
const isProd = true;
console.log(import.meta.env);
export const BASE_URL = import.meta.env.VITE_BASE_URL;
// socket地址
export const WSS_URL = import.meta.env.VITE_WSS_URL;

View File

@@ -55,7 +55,10 @@
},
/* */
"quickapp": {},
/* wx23f86d809ae80259 wx5e79df5996572539 */
/* project.config.json
wx5e79df5996572539
wx23f86d809ae80259
*/
"mp-weixin": {
"appid": "wx5e79df5996572539",
"setting": {

View File

@@ -143,7 +143,7 @@ import {
RECOMMEND_POSTS_TITLE,
SEND_COMMAND_TEXT,
} from "@/constant/constant";
import { WSS_URL } from "@/constant/base";
import { WSS_URL } from "@/request/base/baseUrl";
import { MessageRole, MessageType, CompName } from "../../model/ChatModel";
import ChatTopWelcome from "./ChatTopWelcome.vue";
import ChatTopBgImg from "./ChatTopBgImg.vue";

View File

@@ -1,8 +1,8 @@
import { BASE_URL } from "../../constant/base";
import { BASE_URL } from "@/request/base/baseUrl";
import { goLogin } from "@/hooks/useGoLogin";
/// 请求流式数据的API
const API = '/agent/assistant/chat';
const API = "/agent/assistant/chat";
/**
* 获取AI聊天流式信息仅微信小程序支持
@@ -31,7 +31,7 @@ const stopAbortTask = () => {
activeRequestId = null;
if (currentPromiseReject) {
currentPromiseReject(new Error('请求已被用户终止'));
currentPromiseReject(new Error("请求已被用户终止"));
currentPromiseReject = null;
}
@@ -39,16 +39,16 @@ const stopAbortTask = () => {
// 先移除监听器,再终止请求
const cleanupListeners = () => {
try {
if(requestTask.offChunkReceived) {
console.log("======>offChunkReceived")
if (requestTask.offChunkReceived) {
console.log("======>offChunkReceived");
requestTask.offChunkReceived();
}
if(requestTask.offHeadersReceived) {
console.log("======>offHeadersReceived")
if (requestTask.offHeadersReceived) {
console.log("======>offHeadersReceived");
requestTask.offHeadersReceived();
}
} catch (e) {
console.error('清理事件监听器失败:', e);
console.error("清理事件监听器失败:", e);
}
};
@@ -57,22 +57,22 @@ const stopAbortTask = () => {
// 终止请求
try {
if (requestTask.abort) {
console.log("======>abort")
console.log("======>abort");
requestTask.abort();
}
} catch (e) {
console.log('🛑 终止网络请求失败:', e);
console.log("🛑 终止网络请求失败:", e);
}
requestTask = null;
}
console.log('🛑 请求强制终止完成');
}
console.log("🛑 请求强制终止完成");
};
const agentChatStream = (params, onChunk) => {
return new Promise((resolve, reject) => {
const token = uni.getStorageSync('token');
const token = uni.getStorageSync("token");
const requestId = Date.now().toString(); // 生成唯一请求ID
// 重置状态
@@ -87,21 +87,23 @@ const agentChatStream = (params, onChunk) => {
// 检查数据块是否来自已终止的请求
const isStaleData = (dataRequestId) => {
return dataRequestId === lastRequestId || dataRequestId !== activeRequestId;
return (
dataRequestId === lastRequestId || dataRequestId !== activeRequestId
);
};
// #ifdef MP-WEIXIN
requestTask = uni.request({
url: BASE_URL + API, // 替换为你的接口地址
method: 'POST',
method: "POST",
data: params,
enableChunked: true,
header: {
Accept: 'text/event-stream',
'Content-Type': 'application/json',
Accept: "text/event-stream",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`, // 如需token可加
},
responseType: 'arraybuffer',
responseType: "arraybuffer",
success(res) {
if (!isAborted && !isStaleData(requestId)) {
console.log(`✅ 请求 [${requestId}] 成功`);
@@ -122,30 +124,39 @@ const agentChatStream = (params, onChunk) => {
// 使用 requestId 来验证请求有效性
if (!isAborted && activeRequestId === requestId) {
if (res.statusCode !== 200) {
console.log(`❌ 请求 [${requestId}] 完成但状态错误,状态:`, res.statusCode);
if(res.statusCode === 424) {
uni.setStorageSync('token', '');
console.log(
`❌ 请求 [${requestId}] 完成但状态错误,状态:`,
res.statusCode
);
if (res.statusCode === 424) {
uni.setStorageSync("token", "");
goLogin();
}
if (onChunk) {
onChunk({
error: true,
message: '服务器错误',
detail: res
message: "服务器错误",
detail: res,
});
}
reject(res);
}
} else {
console.log(`❌ 请求 [${requestId}] ${isAborted ? '已终止' : '已过期'}忽略complete回调`);
}
console.log(
`❌ 请求 [${requestId}] ${
isAborted ? "已终止" : "已过期"
}忽略complete回调`
);
}
},
});
requestTask.onHeadersReceived(res => {
requestTask.onHeadersReceived((res) => {
// 使用 requestId 验证请求有效性
if (isAborted || activeRequestId !== requestId) {
console.log(`🚫 Headers [${requestId}] ${isAborted ? '已终止' : '已过期'},忽略`);
console.log(
`🚫 Headers [${requestId}] ${isAborted ? "已终止" : "已过期"},忽略`
);
return;
}
@@ -158,7 +169,7 @@ const agentChatStream = (params, onChunk) => {
onChunk({
error: true,
message: `服务器错误(${status})`,
detail: res
detail: res,
});
}
// 终止异常请求
@@ -168,7 +179,7 @@ const agentChatStream = (params, onChunk) => {
}
});
requestTask.onChunkReceived(res => {
requestTask.onChunkReceived((res) => {
// 立即验证请求有效性
if (isAborted || isStaleData(requestId)) {
console.log(`🚫 数据块 [${requestId}] 已终止或过期,忽略`);
@@ -176,15 +187,15 @@ const agentChatStream = (params, onChunk) => {
}
const base64 = uni.arrayBufferToBase64(res.data);
let data = '';
let data = "";
try {
data = decodeURIComponent(escape(weAtob(base64)));
} catch (e) {
console.error('Base64解码失败:', e);
console.error("Base64解码失败:", e);
return;
}
console.log("📦 onChunkReceivedres:", data)
console.log("📦 onChunkReceivedres:", data);
// 再次验证请求有效性
if (isAborted || activeRequestId !== requestId) {
@@ -193,7 +204,7 @@ const agentChatStream = (params, onChunk) => {
}
const messages = parseSSEChunk(data);
messages.forEach(msg => {
messages.forEach((msg) => {
if (!isAborted && !isStaleData(requestId) && onChunk) {
onChunk(msg);
}
@@ -201,14 +212,16 @@ const agentChatStream = (params, onChunk) => {
});
// #endif
});
}
};
// window.atob兼容性处理
const weAtob = (string) => {
const b64re = /^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
const b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
const b64re =
/^(?:[A-Za-z\d+/]{4})*?(?:[A-Za-z\d+/]{2}(?:==)?|[A-Za-z\d+/]{3}=?)?$/;
const b64 =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
// 去除空白字符
string = String(string).replace(/[\t\n\f\r ]+/g, '');
string = String(string).replace(/[\t\n\f\r ]+/g, "");
// 验证 Base64 编码
if (!b64re.test(string)) {
throw new TypeError(
@@ -218,15 +231,15 @@ const weAtob = (string) => {
}
// 填充字符
string += '=='.slice(2 - (string.length & 3));
string += "==".slice(2 - (string.length & 3));
let bitmap,
result = '',
result = "",
r1,
r2,
i = 0;
for (; i < string.length;) {
for (; i < string.length; ) {
bitmap =
(b64.indexOf(string.charAt(i++)) << 18) |
(b64.indexOf(string.charAt(i++)) << 12) |
@@ -236,10 +249,7 @@ const weAtob = (string) => {
if (r1 === 64) {
result += String.fromCharCode((bitmap >> 16) & 255);
} else if (r2 === 64) {
result += String.fromCharCode(
(bitmap >> 16) & 255,
(bitmap >> 8) & 255
);
result += String.fromCharCode((bitmap >> 16) & 255, (bitmap >> 8) & 255);
} else {
result += String.fromCharCode(
(bitmap >> 16) & 255,
@@ -251,7 +261,6 @@ const weAtob = (string) => {
return result;
};
// 解析SSE分段数据
const parseSSEChunk = (raw) => {
const results = [];
@@ -264,7 +273,7 @@ const parseSSEChunk = (raw) => {
let dataLines = [];
for (const line of lines) {
if (line.startsWith('data:')) {
if (line.startsWith("data:")) {
// 提取data:后面的内容并去除首尾空格
dataLines.push(line.slice(5).trim());
}
@@ -272,18 +281,18 @@ const parseSSEChunk = (raw) => {
if (dataLines.length > 0) {
// 拼接多行数据
const fullData = dataLines.join('\n');
const fullData = dataLines.join("\n");
try {
const obj = JSON.parse(fullData);
results.push(obj);
} catch (e) {
console.warn('⚠️ SSE数据解析失败:', e, '原始数据:', fullData);
console.warn("⚠️ SSE数据解析失败:", e, "原始数据:", fullData);
// 解析失败忽略
}
}
}
return results;
}
};
export { agentChatStream, stopAbortTask }
export { agentChatStream, stopAbortTask };

19
request/base/baseUrl.js Normal file
View File

@@ -0,0 +1,19 @@
const isProd = false;
// 测试
const VITE_BASE_URL_TEST = "https://onefeel.brother7.cn/ingress";
const VITE_WSS_URL_TEST = "wss://onefeel.brother7.cn/ingress/agent/ws/chat";
// 生产
const VITE_BASE_URL_PRO = "https://biz.nianxx.cn";
const VITE_WSS_URL_PRO = "wss://biz.nianxx.cn/agent/ws/chat";
// 环境配置
export const BASE_URL = isProd ? VITE_BASE_URL_PRO : VITE_BASE_URL_TEST;
export const WSS_URL = isProd ? VITE_WSS_URL_PRO : VITE_WSS_URL_TEST;
// =====================================
// 环境配置文件使用方法
// console.log("当前环境:", import.meta.env);
// export const BASE_URL = import.meta.env.VITE_BASE_URL;
// export const WSS_URL = import.meta.env.VITE_WSS_URL;

View File

@@ -1,4 +1,4 @@
import { BASE_URL } from "../../constant/base";
import { BASE_URL } from "./baseUrl";
import { goLogin } from "@/hooks/useGoLogin";
const defaultConfig = {