修复AI工具调用报错

This commit is contained in:
2025-09-17 18:29:54 +08:00
parent dd3f702887
commit 5613cdd6c9
22 changed files with 260 additions and 282 deletions

View File

@@ -1 +0,0 @@
REACT_APP_API_URL=https://infogenie.api.shumengya.top

View File

@@ -1 +0,0 @@
REACT_APP_API_URL=https://infogenie.api.shumengya.top

View File

@@ -1 +0,0 @@
REACT_APP_API_URL=https://infogenie.api.shumengya.top

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
poetry: '/api/aimodelapp/poetry'
}

View File

@@ -10,18 +10,19 @@ const themeInput = document.getElementById('theme');
// 调用后端API
async function callBackendAPI(theme) {
try {
const token = AUTH_CONFIG.getToken();
const headers = {
'Content-Type': 'application/json'
};
// 获取JWT token
const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
if (!token) {
throw new Error('未登录请先登录后使用AI功能');
}
const response = await fetch(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.poetry}`, {
const response = await fetch(`${window.API_CONFIG.baseUrl}/api/aimodelapp/poetry`, {
method: 'POST',
headers: headers,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
theme: theme
})

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
variableNaming: '/api/aimodelapp/variable-naming'
}

View File

@@ -47,7 +47,7 @@ async function callBackendAPI(description) {
throw new Error('未登录请先登录后使用AI功能');
}
const response = await fetch('http://127.0.0.1:5002/api/aimodelapp/variable-naming', {
const response = await fetch(`${window.API_CONFIG.baseUrl}/api/aimodelapp/variable-naming`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
nameAnalysis: '/api/aimodelapp/name-analysis'
}

View File

@@ -193,18 +193,19 @@ async function analyzeName() {
try {
// 调用后端API
const token = AUTH_CONFIG.getToken();
const headers = {
'Content-Type': 'application/json'
};
// 获取JWT token
const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
if (!token) {
throw new Error('未登录请先登录后使用AI功能');
}
const response = await fetch(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.nameAnalysis}`, {
const response = await fetch(`${window.API_CONFIG.baseUrl}/api/aimodelapp/name-analysis`, {
method: 'POST',
headers: headers,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify(requestBody)
});

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
classicalConversion: '/api/aimodelapp/classical_conversion'
}

View File

@@ -12,18 +12,19 @@ const conversionResultContainer = document.getElementById('conversionResult');
// 调用后端API
async function callBackendAPI(modernText, style, articleType) {
try {
const token = AUTH_CONFIG.getToken();
const headers = {
'Content-Type': 'application/json'
};
// 获取JWT token
const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
if (!token) {
throw new Error('未登录请先登录后使用AI功能');
}
const response = await fetch(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.classicalConversion}`, {
const response = await fetch(`${window.API_CONFIG.baseUrl}/api/aimodelapp/classical_conversion`, {
method: 'POST',
headers: headers,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
modern_text: modernText,
style: style,

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
linuxCommand: '/api/aimodelapp/linux-command'
}

View File

@@ -11,7 +11,7 @@ const commandsContainer = document.getElementById('commands');
// 调用后端API
async function callBackendAPI(taskDescription, difficultyLevel) {
try {
const token = AUTH_CONFIG.getToken();
const token = localStorage.getItem('token');
const headers = {
'Content-Type': 'application/json'
};
@@ -20,7 +20,7 @@ async function callBackendAPI(taskDescription, difficultyLevel) {
headers['Authorization'] = `Bearer ${token}`;
}
const response = await fetch(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.linuxCommand}`, {
const response = await fetch(`${window.API_CONFIG.baseUrl}${window.API_CONFIG.endpoints.linuxCommand}`, {
method: 'POST',
headers: headers,
body: JSON.stringify({

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
expressionMaker: '/api/aimodelapp/expression-maker'
}

View File

@@ -1,6 +1,29 @@
// 从配置文件导入设置
// 配置在 env.js 文件中定义
// 表情配置
const CONFIG = {
intensityLevels: {
'low': { color: '#4CAF50' },
'medium': { color: '#FF9800' },
'high': { color: '#F44336' },
'very_high': { color: '#9C27B0' }
},
expressionCategories: {
'emoji': { className: 'emoji' },
'kaomoji': { className: 'kaomoji' },
'combination': { className: 'combination' }
},
expressionStyles: {
'cute': { name: '可爱风', description: '适合表达可爱、萌系情感' },
'cool': { name: '酷炫风', description: '适合表达酷炫、帅气情感' },
'angry': { name: '愤怒风', description: '适合表达愤怒、生气情感' },
'sad': { name: '悲伤风', description: '适合表达悲伤、难过情感' },
'happy': { name: '开心风', description: '适合表达开心、快乐情感' },
'mixed': { name: '混合风', description: '多种风格混合,适应各种情感' }
}
};
// DOM 元素
const textInput = document.getElementById('text-input');
const styleSelect = document.getElementById('style-select');
@@ -18,7 +41,7 @@ async function callBackendAPI(text, style) {
throw new Error('未登录请先登录后使用AI功能');
}
const response = await fetch(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.expressionMaker}`, {
const response = await fetch(`${window.API_CONFIG.baseUrl}/api/aimodelapp/expression-maker`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@@ -3,7 +3,7 @@
// API配置
window.API_CONFIG = {
baseUrl: 'http://127.0.0.1:5002',
baseUrl: window.parent.ENV_CONFIG.API_URL,
endpoints: {
translation: '/api/aimodelapp/translation'
}

View File

@@ -11,18 +11,19 @@ const translationResultContainer = document.getElementById('translationResult');
// 调用后端API
async function callBackendAPI(sourceText, targetLanguage) {
try {
const token = AUTH_CONFIG.getToken();
const headers = {
'Content-Type': 'application/json'
};
// 获取JWT token
const token = localStorage.getItem('token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
if (!token) {
throw new Error('未登录请先登录后使用AI功能');
}
const response = await fetch(`${API_CONFIG.baseUrl}${API_CONFIG.endpoints.translation}`, {
const response = await fetch(`${window.API_CONFIG.baseUrl}/api/aimodelapp/translation`, {
method: 'POST',
headers: headers,
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
},
body: JSON.stringify({
source_text: sourceText,
target_language: targetLanguage

View File

@@ -1,228 +0,0 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>API超时修复测试</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f5f5f7;
}
.container {
background: white;
border-radius: 12px;
padding: 30px;
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
h1 {
color: #1d1d1f;
text-align: center;
margin-bottom: 30px;
}
.test-section {
margin-bottom: 30px;
padding: 20px;
border: 1px solid #e5e5e7;
border-radius: 8px;
}
.test-section h3 {
color: #333;
margin-top: 0;
}
input, select, button {
width: 100%;
padding: 12px;
margin: 8px 0;
border: 1px solid #d2d2d7;
border-radius: 8px;
font-size: 16px;
}
button {
background: #007aff;
color: white;
border: none;
cursor: pointer;
transition: background 0.3s;
}
button:hover {
background: #0056b3;
}
button:disabled {
background: #ccc;
cursor: not-allowed;
}
.result {
margin-top: 15px;
padding: 15px;
border-radius: 8px;
white-space: pre-wrap;
font-family: monospace;
font-size: 14px;
}
.success {
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
}
.error {
background: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
}
.loading {
background: #fff3cd;
border: 1px solid #ffeaa7;
color: #856404;
}
.status {
font-weight: bold;
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container">
<h1>🔧 API超时修复测试</h1>
<div class="test-section">
<h3>🎭 表情制作器API测试</h3>
<input type="text" id="expressionText" placeholder="输入要生成表情的文字" value="开心">
<select id="expressionStyle">
<option value="mixed">混合风格</option>
<option value="emoji">仅Emoji</option>
<option value="kaomoji">仅颜文字</option>
<option value="cute">可爱风格</option>
<option value="cool">酷炫风格</option>
</select>
<button onclick="testExpressionAPI()">测试表情API</button>
<div id="expressionResult"></div>
</div>
<div class="test-section">
<h3>📝 变量命名API测试</h3>
<input type="text" id="variableDesc" placeholder="输入变量描述" value="用户的年龄">
<button onclick="testVariableAPI()">测试变量命名API</button>
<div id="variableResult"></div>
</div>
</div>
<script>
async function testExpressionAPI() {
const text = document.getElementById('expressionText').value.trim();
const style = document.getElementById('expressionStyle').value;
const resultDiv = document.getElementById('expressionResult');
if (!text) {
showResult(resultDiv, '请输入文字内容', 'error');
return;
}
showResult(resultDiv, '正在调用表情制作API...\n请耐心等待最多90秒', 'loading');
const startTime = Date.now();
try {
const response = await fetch('http://127.0.0.1:5002/api/aimodelapp/expression-maker', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: text,
style: style
})
});
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP ${response.status}`);
}
const data = await response.json();
if (data.success) {
let resultText = `✅ API调用成功\n耗时: ${duration}\n\n`;
resultText += `表情结果:\n${JSON.stringify(data.expressions, null, 2)}`;
showResult(resultDiv, resultText, 'success');
} else {
throw new Error(data.error || '未知错误');
}
} catch (error) {
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
showResult(resultDiv, `❌ API调用失败\n耗时: ${duration}\n错误: ${error.message}`, 'error');
}
}
async function testVariableAPI() {
const description = document.getElementById('variableDesc').value.trim();
const resultDiv = document.getElementById('variableResult');
if (!description) {
showResult(resultDiv, '请输入变量描述', 'error');
return;
}
showResult(resultDiv, '正在调用变量命名API...\n请耐心等待最多90秒', 'loading');
const startTime = Date.now();
try {
const response = await fetch('http://127.0.0.1:5002/api/aimodelapp/variable-naming', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
description: description
})
});
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.error || `HTTP ${response.status}`);
}
const data = await response.json();
if (data.success) {
let resultText = `✅ API调用成功\n耗时: ${duration}\n\n`;
resultText += `变量建议:\n${JSON.stringify(data.suggestions, null, 2)}`;
showResult(resultDiv, resultText, 'success');
} else {
throw new Error(data.error || '未知错误');
}
} catch (error) {
const endTime = Date.now();
const duration = ((endTime - startTime) / 1000).toFixed(2);
showResult(resultDiv, `❌ API调用失败\n耗时: ${duration}\n错误: ${error.message}`, 'error');
}
}
function showResult(element, message, type) {
element.innerHTML = `<div class="result ${type}"><div class="status">${getStatusText(type)}</div>${message}</div>`;
}
function getStatusText(type) {
switch(type) {
case 'success': return '✅ 成功';
case 'error': return '❌ 错误';
case 'loading': return '⏳ 加载中';
default: return '';
}
}
</script>
</body>
</html>

View File

@@ -243,6 +243,7 @@ const Header = () => {
<NavLink to="/60sapi">API聚合应用</NavLink>
<NavLink to="/smallgame">玩玩小游戏</NavLink>
<NavLink to="/aimodel">AI工具</NavLink>
<NavLink to="/profile">个人中心</NavLink>
</Nav>
<UserSection>
@@ -302,6 +303,9 @@ const Header = () => {
<MobileNavLink to="/aimodel" onClick={handleMenuClose}>
🤖AI工具
</MobileNavLink>
<MobileNavLink to="/profile" onClick={handleMenuClose}>
👤个人中心
</MobileNavLink>
{isLoggedIn && user ? (
<>

View File

@@ -0,0 +1,40 @@
// 环境配置文件
// 统一管理所有环境变量配置
// 统一环境配置
const config = {
API_URL: 'https://infogenie.api.shumengya.top',
DEBUG: true,
LOG_LEVEL: 'debug'
};
// 导出配置对象
export const ENV_CONFIG = {
// API相关配置
API_URL: config.API_URL,
// 调试相关配置
DEBUG: config.DEBUG,
LOG_LEVEL: config.LOG_LEVEL,
// 应用信息
APP_NAME: 'InfoGenie',
APP_VERSION: '1.0.0'
};
// 兼容性函数:模拟 process.env 的行为
export const getEnvVar = (key, defaultValue = '') => {
switch (key) {
case 'REACT_APP_API_URL':
return ENV_CONFIG.API_URL;
default:
return process.env[key] || defaultValue;
}
};
// 将配置暴露到window对象上以便子应用iframe可以访问
if (typeof window !== 'undefined') {
window.ENV_CONFIG = ENV_CONFIG;
}
export default ENV_CONFIG;

View File

@@ -1,4 +1,5 @@
import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import { useUser } from '../contexts/UserContext';
import { FiUser, FiStar, FiTrendingUp, FiGift, FiCalendar, FiAward } from 'react-icons/fi';
@@ -68,11 +69,11 @@ const StatsGrid = styled.div`
margin-bottom: 24px;
@media (max-width: 768px) {
grid-template-columns: repeat(2, 1fr);
gap: 12px;
}
@media (max-width: 480px) {
grid-template-columns: 1fr;
gap: 8px;
}
`;
@@ -90,6 +91,16 @@ const StatCard = styled.div`
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(168, 230, 207, 0.3);
}
@media (max-width: 768px) {
padding: 16px;
border-radius: 12px;
}
@media (max-width: 480px) {
padding: 12px 8px;
border-radius: 10px;
}
`;
const StatIcon = styled.div`
@@ -103,6 +114,21 @@ const StatIcon = styled.div`
margin: 0 auto 12px;
color: white;
font-size: 20px;
@media (max-width: 768px) {
width: 40px;
height: 40px;
font-size: 18px;
margin: 0 auto 8px;
}
@media (max-width: 480px) {
width: 32px;
height: 32px;
font-size: 16px;
margin: 0 auto 6px;
border-radius: 8px;
}
`;
const StatValue = styled.div`
@@ -110,11 +136,29 @@ const StatValue = styled.div`
font-weight: bold;
color: #2e7d32;
margin-bottom: 4px;
@media (max-width: 768px) {
font-size: 20px;
}
@media (max-width: 480px) {
font-size: 16px;
margin-bottom: 2px;
}
`;
const StatLabel = styled.div`
font-size: 14px;
color: #666;
@media (max-width: 768px) {
font-size: 13px;
}
@media (max-width: 480px) {
font-size: 11px;
line-height: 1.2;
}
`;
const CheckinSection = styled.div`
@@ -199,8 +243,60 @@ const SuccessMessage = styled.div`
text-align: center;
`;
const LoginPrompt = styled.div`
background: rgba(255, 255, 255, 0.95);
border-radius: 20px;
padding: 60px 40px;
text-align: center;
box-shadow: 0 8px 32px rgba(168, 230, 207, 0.3);
backdrop-filter: blur(10px);
border: 1px solid rgba(168, 230, 207, 0.2);
margin-bottom: 40px;
`;
const LoginIcon = styled.div`
font-size: 64px;
margin-bottom: 24px;
`;
const LoginTitle = styled.h2`
font-size: 24px;
font-weight: bold;
color: #2e7d32;
margin-bottom: 16px;
`;
const LoginText = styled.p`
color: #666;
font-size: 16px;
line-height: 1.6;
margin-bottom: 24px;
`;
const LoginButton = styled.button`
background: linear-gradient(135deg, #81c784 0%, #a5d6a7 100%);
color: white;
border: none;
padding: 14px 32px;
border-radius: 16px;
font-size: 16px;
font-weight: 600;
cursor: pointer;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
gap: 8px;
box-shadow: 0 4px 16px rgba(129, 199, 132, 0.3);
&:hover {
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(129, 199, 132, 0.4);
}
`;
const UserProfilePage = () => {
const { user } = useUser();
const { user, isLoggedIn, isLoading } = useUser();
const navigate = useNavigate();
const [gameData, setGameData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
@@ -226,9 +322,17 @@ const UserProfilePage = () => {
return null;
};
const handleLogin = () => {
navigate('/login');
};
useEffect(() => {
if (isLoggedIn) {
fetchGameData();
}, []);
} else {
setLoading(false);
}
}, [isLoggedIn]);
const fetchGameData = async () => {
try {
@@ -280,6 +384,38 @@ const UserProfilePage = () => {
return Math.floor(100 * Math.pow(1.2, level));
};
if (isLoading) {
return (
<ProfileContainer>
<Container>
<LoadingSpinner>加载中...</LoadingSpinner>
</Container>
</ProfileContainer>
);
}
if (!isLoggedIn) {
return (
<ProfileContainer>
<Container>
<LoginPrompt>
<LoginIcon>🔒</LoginIcon>
<LoginTitle>需要登录访问</LoginTitle>
<LoginText>
个人中心需要登录后才能查看请先登录您的账户
<br />
登录后即可查看您的个人信息萌芽币余额签到记录等
</LoginText>
<LoginButton onClick={handleLogin}>
<FiUser />
立即登录
</LoginButton>
</LoginPrompt>
</Container>
</ProfileContainer>
);
}
if (loading) {
return (
<ProfileContainer>

View File

@@ -1,9 +1,10 @@
import axios from 'axios';
import toast from 'react-hot-toast';
import { ENV_CONFIG } from '../config/env.js';
// 创建axios实例
const api = axios.create({
baseURL: process.env.REACT_APP_API_URL || 'https://infogenie.api.shumengya.top',
baseURL: ENV_CONFIG.API_URL,
timeout: 10000,
withCredentials: true, // 支持携带cookie
headers: {
@@ -12,8 +13,9 @@ const api = axios.create({
});
// 打印当前使用的API URL便于调试
console.log('🔧 环境变量 REACT_APP_API_URL:', process.env.REACT_APP_API_URL);
console.log('🌐 最终使用的 API Base URL:', process.env.REACT_APP_API_URL || 'https://infogenie.api.shumengya.top');
if (ENV_CONFIG.DEBUG) {
console.log('🌐 使用的 API Base URL:', ENV_CONFIG.API_URL);
}
// 请求拦截器
api.interceptors.request.use(