hongjli
2025-05-27 dff84a56d8a5d8a759757a9b1c9408f43f5c7705
聊天页面增加后台获取key接口
已修改1个文件
69 ■■■■ 文件已修改
src/app/chat/page.tsx 69 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/app/chat/page.tsx
@@ -487,6 +487,9 @@
  // 在组件顶部添加显示/隐藏密码的状态
  const [showApiKey, setShowApiKey] = useState(false);
  // 添加API密钥加载状态
  const [isLoadingApiKey, setIsLoadingApiKey] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const errorTimeoutRef = useRef<any>(null);
@@ -496,6 +499,44 @@
  // 分离消息输入状态,避免触发不必要的重渲染
  const messageInputRef = useRef<HTMLTextAreaElement>(null);
  const [localMessage, setLocalMessage] = useState('');
  // 添加获取API密钥的函数
  const fetchApiKey = async () => {
    setIsLoadingApiKey(true);
    try {
      const response = await fetch('http://121.43.139.99:8080/api/secret-key', {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      });
      if (!response.ok) {
        throw new Error(`获取密钥失败: HTTP ${response.status}`);
      }
      const result = await response.json();
      console.log('API响应:', result);
      // 按照接口文档格式解析响应
      if (result.code === 200 && result.data && result.data.key) {
        const apiKeyValue = result.data.key;
        setApiKey(apiKeyValue);
        setError(null);
        console.log('成功获取API密钥:', apiKeyValue);
        return apiKeyValue;
      } else {
        throw new Error(result.message || '获取密钥失败:响应格式不正确');
      }
    } catch (err) {
      console.error('获取API密钥失败:', err);
      const errorMessage = err instanceof Error ? err.message : '获取密钥时发生未知错误';
      showErrorMessage(`密钥获取失败: ${errorMessage}`);
      return null;
    } finally {
      setIsLoadingApiKey(false);
    }
  };
  
  const handleMessageChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    // 只更新本地状态,不触发全局重渲染
@@ -528,13 +569,12 @@
  }, [message]);
  useEffect(() => {
    // 获取存储的API Key
    const storedApiKey = localStorage.getItem('api-key');
    if (storedApiKey) {
      setApiKey(storedApiKey);
    } else {
      setShowApiKeyInput(true);
    }
    // 组件加载时从API获取密钥
    const initializeApiKey = async () => {
      await fetchApiKey();
    };
    initializeApiKey();
  }, []);
  useEffect(() => {
@@ -604,9 +644,16 @@
    // 从window对象获取消息内容
    const inputMessage = (window as any).messageToSend || '';
    if (!inputMessage.trim() || !isMessageComplete) return;
    if (!apiKey) {
      showErrorMessage('请先设置API Key');
      return;
    // 检查API密钥,如果没有则尝试获取
    let currentApiKey = apiKey;
    if (!currentApiKey) {
      showErrorMessage('正在获取API密钥...');
      currentApiKey = await fetchApiKey();
      if (!currentApiKey) {
        showErrorMessage('无法获取API密钥,请检查网络连接');
        return;
      }
    }
    setIsStreaming(true);
@@ -652,7 +699,7 @@
      const response = await fetch(`${BASE_URL}/v1/chat-messages`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${apiKey}`,
          'Authorization': `Bearer ${currentApiKey}`,
          'Content-Type': 'application/json',
        },
        mode: 'cors',