feat: 初始化Vue3项目并添加核心功能模块
新增项目基础结构,包括Vue3、Pinia、Element Plus等核心依赖 添加路由配置和用户认证状态管理 实现销售数据看板、客户画像、团队管理等核心功能模块 集成图表库和API请求工具,完成基础样式配置
This commit is contained in:
168
my-vue-app/src/utils/ChatService.js
Normal file
168
my-vue-app/src/utils/ChatService.js
Normal file
@@ -0,0 +1,168 @@
|
||||
import axios from 'axios';
|
||||
|
||||
// Dify API的基础URL,可以根据你的实际部署地址进行修改
|
||||
const BaseUrl = 'https://ai.nycjy1.cn/v1'; // 示例: 替换成你的 Dify API 地址
|
||||
|
||||
/**
|
||||
* 处理从Dify API返回的流式数据块。
|
||||
* @param chunk - 从服务器接收到的数据块字符串。
|
||||
* @param options - 包含当前状态和回调函数的对象。
|
||||
* @returns 更新后的状态对象。
|
||||
*/
|
||||
function handleStreamResponse(chunk, options) {
|
||||
try {
|
||||
// 忽略空的数据块
|
||||
if (!chunk.trim()) {
|
||||
return options;
|
||||
}
|
||||
|
||||
// 流式数据可能包含多个 "data: {...}" 块,它们由两个换行符分隔
|
||||
const lines = chunk.split('\n\n');
|
||||
|
||||
for (const line of lines) {
|
||||
// 跳过无效行或非数据行
|
||||
if (!line.trim() || !line.startsWith('data:')) continue;
|
||||
|
||||
// 提取 "data:" 后面的JSON字符串
|
||||
const jsonStr = line.slice(5).trim();
|
||||
if (!jsonStr) continue;
|
||||
|
||||
try {
|
||||
// 确保是完整的JSON对象
|
||||
if (!jsonStr.startsWith('{') || !jsonStr.endsWith('}')) {
|
||||
console.warn('接收到不完整的JSON对象:', jsonStr);
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = JSON.parse(jsonStr);
|
||||
|
||||
// 事件类型为 'message',表示正在接收AI的回答
|
||||
if (data.event === 'message') {
|
||||
const newContent = data.answer || '';
|
||||
options.fullResponse += newContent; // 将新的内容追加到完整响应中
|
||||
|
||||
// 调用实时更新回调函数
|
||||
options.onMessageUpdate({
|
||||
content: options.fullResponse,
|
||||
isStreaming: true
|
||||
});
|
||||
|
||||
// 事件类型为 'message_end',表示消息流结束
|
||||
} else if (data.event === 'message_end') {
|
||||
options.isStreamEnded = true;
|
||||
|
||||
// 调用最终更新回调函数
|
||||
options.onMessageUpdate({
|
||||
content: options.fullResponse,
|
||||
isStreaming: false
|
||||
});
|
||||
|
||||
// 调用流结束的回调
|
||||
options.onStreamEnd();
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.warn('JSON解析错误:', {
|
||||
error: parseError,
|
||||
rawData: jsonStr,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('流处理时发生错误:', e);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* 一个简单的Dify聊天服务类。
|
||||
*/
|
||||
export class SimpleChatService {
|
||||
constructor(apiKey, baseUrl = BaseUrl) {
|
||||
if (!apiKey) {
|
||||
throw new Error("API Key是必须的。");
|
||||
}
|
||||
this.apiKey = apiKey;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息到Dify API并处理流式响应。
|
||||
* @param userMessage - 用户发送的消息。
|
||||
* @param onMessageUpdate - 当收到新数据块时调用的回调函数。
|
||||
* @param onStreamEnd - 当流结束时调用的回调函数。
|
||||
* @param abortSignal - 用于取消请求的AbortSignal。
|
||||
*/
|
||||
async sendMessage(
|
||||
userMessage,
|
||||
onMessageUpdate,
|
||||
onStreamEnd,
|
||||
abortSignal = null
|
||||
) {
|
||||
const params = {
|
||||
inputs: {},
|
||||
query: userMessage,
|
||||
response_mode: 'streaming', // 声明需要流式响应
|
||||
conversation_id: '', // 如果需要继续之前的对话,请传入对应的ID
|
||||
user: 'web-user-axios-simple',
|
||||
auto_generate_name: true
|
||||
};
|
||||
|
||||
let state = {
|
||||
fullResponse: '',
|
||||
isStreamEnded: false,
|
||||
};
|
||||
|
||||
// 用于跟踪已处理的响应文本长度
|
||||
let processedLength = 0;
|
||||
|
||||
try {
|
||||
await axios({
|
||||
method: 'POST',
|
||||
url: `${this.baseUrl}/chat-messages`,
|
||||
data: params,
|
||||
headers: {
|
||||
'Authorization': `Bearer ${this.apiKey}`,
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
responseType: 'text', // 必须设置为 'text' 以便处理流式响应
|
||||
signal: abortSignal, // 关联取消信号
|
||||
onDownloadProgress: (progressEvent) => {
|
||||
// 获取自上次回调以来新增的文本部分
|
||||
const newChunk = progressEvent.event.target.responseText.substring(processedLength);
|
||||
processedLength = progressEvent.event.target.responseText.length;
|
||||
|
||||
// 将新的数据块传递给处理函数
|
||||
state = handleStreamResponse(newChunk, {
|
||||
...state,
|
||||
onMessageUpdate,
|
||||
onStreamEnd,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 检查请求完成后,流是否已正常结束
|
||||
if (!state.isStreamEnded) {
|
||||
console.warn("请求已完成,但未收到 'message_end' 事件。");
|
||||
onMessageUpdate({
|
||||
content: state.fullResponse,
|
||||
isStreaming: false
|
||||
});
|
||||
onStreamEnd();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (axios.isCancel(error)) {
|
||||
console.log('请求已被用户取消。');
|
||||
} else {
|
||||
console.error('发送消息失败:', error);
|
||||
onMessageUpdate({
|
||||
content: '抱歉,发送消息失败,请检查API Key或网络连接后重试。',
|
||||
isStreaming: false
|
||||
});
|
||||
}
|
||||
// 确保在出错或取消时也调用 onStreamEnd
|
||||
onStreamEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
226
my-vue-app/src/utils/https.js
Normal file
226
my-vue-app/src/utils/https.js
Normal file
@@ -0,0 +1,226 @@
|
||||
import axios from 'axios'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import router from '@/router'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
|
||||
// 创建axios实例
|
||||
const service = axios.create({
|
||||
baseURL: 'http://192.168.15.54:8890' || '', // API基础路径,支持完整URL
|
||||
timeout: 15000, // 请求超时时间
|
||||
headers: {
|
||||
'Content-Type': 'application/json;charset=UTF-8'
|
||||
}
|
||||
})
|
||||
|
||||
// 请求拦截器
|
||||
service.interceptors.request.use(
|
||||
config => {
|
||||
// 在发送请求之前做些什么
|
||||
console.log('发送请求:', config)
|
||||
|
||||
// 添加token到请求头
|
||||
const userStore = useUserStore()
|
||||
const token = userStore.token
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
// 添加时间戳防止缓存
|
||||
if (config.method === 'get') {
|
||||
config.params = {
|
||||
...config.params,
|
||||
_t: Date.now()
|
||||
}
|
||||
}
|
||||
|
||||
// 显示加载状态
|
||||
if (config.showLoading !== false) {
|
||||
// 可以在这里添加全局loading
|
||||
console.log('显示加载中...')
|
||||
}
|
||||
|
||||
return config
|
||||
},
|
||||
error => {
|
||||
// 对请求错误做些什么
|
||||
console.error('请求错误:', error)
|
||||
ElMessage.error('请求发送失败')
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// 响应拦截器
|
||||
service.interceptors.response.use(
|
||||
response => {
|
||||
// 隐藏加载状态
|
||||
console.log('隐藏加载中...')
|
||||
|
||||
// 对响应数据做点什么
|
||||
console.log('收到响应:', response)
|
||||
|
||||
const { data, status } = response
|
||||
|
||||
// HTTP状态码检查
|
||||
if (status === 200) {
|
||||
// 根据后端返回的数据结构进行判断
|
||||
if (data.code === 200 || data.success === true) {
|
||||
// 请求成功
|
||||
return data
|
||||
} else if (data.code === 401) {
|
||||
// token过期或无效
|
||||
ElMessage.error('登录已过期,请重新登录')
|
||||
const userStore = useUserStore()
|
||||
userStore.logout()
|
||||
router.push('/login')
|
||||
return Promise.reject(new Error('登录已过期'))
|
||||
} else if (data.code === 403) {
|
||||
// 权限不足
|
||||
ElMessage.error('权限不足,无法访问')
|
||||
return Promise.reject(new Error('权限不足'))
|
||||
} else {
|
||||
// 其他业务错误
|
||||
const errorMsg = data.message || data.msg || '请求失败'
|
||||
ElMessage.error(errorMsg)
|
||||
return Promise.reject(new Error(errorMsg))
|
||||
}
|
||||
} else {
|
||||
ElMessage.error('网络请求失败')
|
||||
return Promise.reject(new Error('网络请求失败'))
|
||||
}
|
||||
},
|
||||
error => {
|
||||
// 隐藏加载状态
|
||||
console.log('隐藏加载中...')
|
||||
|
||||
// 对响应错误做点什么
|
||||
console.error('响应错误:', error)
|
||||
|
||||
let errorMessage = '网络错误'
|
||||
|
||||
if (error.response) {
|
||||
// 服务器返回了错误状态码
|
||||
const { status, data } = error.response
|
||||
|
||||
switch (status) {
|
||||
case 400:
|
||||
errorMessage = data.message || '请求参数错误'
|
||||
break
|
||||
case 401:
|
||||
errorMessage = '登录已过期,请重新登录'
|
||||
const userStore = useUserStore()
|
||||
userStore.logout()
|
||||
router.push('/login')
|
||||
break
|
||||
case 403:
|
||||
errorMessage = '权限不足,无法访问'
|
||||
break
|
||||
case 404:
|
||||
errorMessage = '请求的资源不存在'
|
||||
break
|
||||
case 500:
|
||||
errorMessage = '服务器内部错误'
|
||||
break
|
||||
case 502:
|
||||
errorMessage = '网关错误'
|
||||
break
|
||||
case 503:
|
||||
errorMessage = '服务不可用'
|
||||
break
|
||||
case 504:
|
||||
errorMessage = '网关超时'
|
||||
break
|
||||
default:
|
||||
errorMessage = data.message || `请求失败 (${status})`
|
||||
}
|
||||
} else if (error.request) {
|
||||
// 请求已发出但没有收到响应
|
||||
errorMessage = '网络连接超时,请检查网络'
|
||||
} else {
|
||||
// 其他错误
|
||||
errorMessage = error.message || '请求失败'
|
||||
}
|
||||
|
||||
ElMessage.error(errorMessage)
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
// 封装常用的请求方法
|
||||
const http = {
|
||||
// GET请求
|
||||
get(url, params = {}, config = {}) {
|
||||
return service({
|
||||
method: 'get',
|
||||
url,
|
||||
params,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
// POST请求
|
||||
post(url, data = {}, config = {}) {
|
||||
return service({
|
||||
method: 'post',
|
||||
url,
|
||||
data,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
// PUT请求
|
||||
put(url, data = {}, config = {}) {
|
||||
return service({
|
||||
method: 'put',
|
||||
url,
|
||||
data,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
// DELETE请求
|
||||
delete(url, params = {}, config = {}) {
|
||||
return service({
|
||||
method: 'delete',
|
||||
url,
|
||||
params,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
// PATCH请求
|
||||
patch(url, data = {}, config = {}) {
|
||||
return service({
|
||||
method: 'patch',
|
||||
url,
|
||||
data,
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
// 文件上传
|
||||
upload(url, formData, config = {}) {
|
||||
return service({
|
||||
method: 'post',
|
||||
url,
|
||||
data: formData,
|
||||
headers: {
|
||||
'Content-Type': 'multipart/form-data'
|
||||
},
|
||||
...config
|
||||
})
|
||||
},
|
||||
|
||||
// 文件下载
|
||||
download(url, params = {}, config = {}) {
|
||||
return service({
|
||||
method: 'get',
|
||||
url,
|
||||
params,
|
||||
responseType: 'blob',
|
||||
...config
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 导出axios实例和封装的方法
|
||||
export default http
|
||||
export { service }
|
||||
Reference in New Issue
Block a user