ShopTRAINING/test/立即测试CORS.py

115 lines
4.3 KiB
Python
Raw Normal View History

2025-07-02 11:05:23 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
立即测试CORS配置 - 模拟浏览器请求
"""
import requests
import json
def immediate_cors_test():
"""立即测试CORS模拟浏览器行为"""
api_base = "http://127.0.0.1:5000"
print("🔥 立即CORS测试 - 模拟浏览器请求")
print("=" * 50)
# 模拟浏览器的标准头部
browser_headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Origin': 'http://localhost:5173',
'Referer': 'http://localhost:5173/',
'Content-Type': 'application/json'
}
# 测试序列
tests = [
("/api/health", "GET", "基础健康检查"),
("/api/stores", "GET", "店铺列表"),
("/api/products", "GET", "产品列表"),
("/api/training", "GET", "训练任务列表")
]
for endpoint, method, description in tests:
print(f"\n🧪 测试: {description}")
print(f"📍 {method} {endpoint}")
try:
# 1. 先发送OPTIONS预检请求浏览器会自动发送
print(" 1⃣ OPTIONS预检请求...")
options_response = requests.options(
f"{api_base}{endpoint}",
headers=browser_headers,
timeout=5
)
print(f" 状态: {options_response.status_code}")
print(f" Allow-Origin: {options_response.headers.get('Access-Control-Allow-Origin', 'MISSING')}")
print(f" Allow-Methods: {options_response.headers.get('Access-Control-Allow-Methods', 'MISSING')}")
print(f" Allow-Headers: {options_response.headers.get('Access-Control-Allow-Headers', 'MISSING')}")
# 2. 发送实际请求
print(" 2⃣ 实际GET请求...")
if method == "GET":
actual_response = requests.get(
f"{api_base}{endpoint}",
headers=browser_headers,
timeout=5
)
else:
continue
print(f" 状态: {actual_response.status_code}")
print(f" Allow-Origin: {actual_response.headers.get('Access-Control-Allow-Origin', 'MISSING')}")
if actual_response.status_code == 200:
print(" ✅ 请求成功")
else:
print(f" ❌ 请求失败: {actual_response.status_code}")
print(f" 错误详情: {actual_response.text[:200]}")
except requests.exceptions.ConnectionError:
print(" ❌ 连接失败 - API服务器未启动")
break
except Exception as e:
print(f" ❌ 异常: {e}")
# 特别测试一个可能有问题的端点
print(f"\n🎯 特别测试: /api/stores (问题端点)")
try:
# 完全模拟浏览器的fetch请求
test_response = requests.get(
f"{api_base}/api/stores",
headers={
'Origin': 'http://localhost:5173',
'Referer': 'http://localhost:5173/',
'Accept': 'application/json',
'Content-Type': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
},
timeout=5
)
print(f"状态码: {test_response.status_code}")
print(f"响应头:")
for header, value in test_response.headers.items():
if 'access-control' in header.lower() or 'cors' in header.lower():
print(f" {header}: {value}")
if test_response.status_code == 200:
print("✅ /api/stores 端点工作正常")
else:
print(f"❌ /api/stores 端点返回: {test_response.status_code}")
except Exception as e:
print(f"❌ /api/stores 测试失败: {e}")
print(f"\n" + "=" * 50)
print("💡 如果看到所有 'Allow-Origin: *'CORS就配置正确了")
print("🔄 请重启API服务器后重新测试")
if __name__ == "__main__":
immediate_cors_test()