前端从 localhost:5173
访问 company.citupro.com:5500
的API时出现CORS错误:
Access to XMLHttpRequest at 'http://company.citupro.com:5500/api/parse/get-calendar-info?date=2025-08-09'
from origin 'http://localhost:5173' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
app/config/cors.py
app/__init__.py
CORS(app, **CORS_OPTIONS)
配置当前配置: 允许任意前端地址访问
# 在 app/config/cors.py 中
ALLOW_ALL_ORIGINS = True # 启用最灵活的配置
# 支持任意Origin,包括但不限于:
# - http://localhost:5173
# - http://192.168.3.218:5173
# - http://10.0.0.1:3000
# - http://172.16.1.100:8080
# - 以及任何其他前端地址
其他配置选项:
# 方案2: 允许特定IP网段
ALLOWED_IP_RANGES = [
"192.168.0.0/16", # 局域网IP段
"10.0.0.0/8", # 内网IP段
"172.16.0.0/12", # 内网IP段
]
# 方案3: 固定地址列表
ALLOWED_ORIGINS = [
"http://localhost:5173",
"http://your-frontend-ip:port",
]
ALLOWED_METHODS = [
"GET", "POST", "PUT", "DELETE", "OPTIONS"
]
ALLOWED_HEADERS = [
"Content-Type", "Authorization", "X-Requested-With",
"Accept", "Origin", "Cache-Control", "X-File-Name"
]
EXPOSED_HEADERS = [
"Content-Type", "Content-Length",
"Content-Disposition", "X-Total-Count"
]
# 测试灵活CORS配置(推荐)
python test_flexible_cors.py
# 测试特定IP地址
python test_cors_new_ip.py
# 快速验证
python quick_verify_cors.py
修改CORS配置后,需要重启Flask应用:
# 如果使用Python直接运行
python application.py
# 如果使用Flask命令
flask run --host=0.0.0.0 --port=5500
const response = await fetch('/api/parse/get-calendar-info?date=${date}', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
credentials: 'include' // 如果需要发送cookies
});
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
if (error.name === 'TypeError' && error.message.includes('CORS')) {
console.error('CORS错误:请检查服务器配置');
}
throw error;
}
确保安装了正确版本的Flask-CORS:
pip install Flask-CORS==4.0.0
确保服务器防火墙允许5500端口的访问。
如果使用Nginx等反向代理,确保代理配置正确转发CORS头部。
在生产环境中,建议: