ShopTRAINING/test/测试5174端口CORS.html

184 lines
7.7 KiB
HTML
Raw Normal View History

2025-07-02 11:05:23 +08:00
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>测试5174端口CORS</title>
<style>
body { font-family: Arial, sans-serif; padding: 20px; max-width: 1200px; margin: 0 auto; }
.info { background: #e3f2fd; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
.test-btn { background: #2196F3; color: white; padding: 10px 20px; border: none; border-radius: 5px; margin: 5px; cursor: pointer; }
.test-btn:hover { background: #1976D2; }
.result { margin: 10px 0; padding: 15px; border-radius: 5px; font-family: monospace; }
.success { background: #c8e6c9; color: #1b5e20; }
.error { background: #ffcdd2; color: #b71c1c; }
.warning { background: #fff9c4; color: #f57f17; }
</style>
</head>
<body>
<h1>🔍 测试端口5174的CORS配置</h1>
<div class="info">
<p><strong>当前页面地址:</strong> <span id="currentUrl"></span></p>
<p><strong>API服务器地址:</strong> http://127.0.0.1:5000</p>
<p><strong>前端应用地址:</strong> http://localhost:5174</p>
<p><strong>说明:</strong> 此页面模拟从localhost:5174发起的请求</p>
</div>
<div>
<button class="test-btn" onclick="testBasicCORS()">测试基础CORS</button>
<button class="test-btn" onclick="testStoresAPI()">测试/api/stores</button>
<button class="test-btn" onclick="testAllAPIs()">测试所有API端点</button>
<button class="test-btn" onclick="clearResults()">清空结果</button>
</div>
<div id="results"></div>
<script>
const API_BASE = 'http://127.0.0.1:5000';
const resultsDiv = document.getElementById('results');
// 显示当前页面URL
document.getElementById('currentUrl').textContent = window.location.href;
function log(message, type = 'info') {
const div = document.createElement('div');
div.className = `result ${type}`;
const time = new Date().toLocaleTimeString();
div.innerHTML = `[${time}] ${message}`;
resultsDiv.appendChild(div);
}
function clearResults() {
resultsDiv.innerHTML = '';
}
async function testBasicCORS() {
log('🧪 开始基础CORS测试...', 'warning');
try {
const response = await fetch(`${API_BASE}/api/health`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'cors' // 明确指定CORS模式
});
if (response.ok) {
const data = await response.json();
log(`✅ 基础CORS测试成功状态: ${data.status}`, 'success');
// 显示CORS相关响应头
const corsHeaders = [
'access-control-allow-origin',
'access-control-allow-methods',
'access-control-allow-headers'
];
log('📋 响应头信息:', 'warning');
corsHeaders.forEach(header => {
const value = response.headers.get(header);
if (value) {
log(` ${header}: ${value}`, 'success');
}
});
} else {
log(`❌ 请求失败: HTTP ${response.status}`, 'error');
}
} catch (error) {
log(`❌ CORS错误: ${error.message}`, 'error');
log('💡 请检查浏览器控制台的详细错误信息', 'warning');
}
}
async function testStoresAPI() {
log('🏪 测试/api/stores端点...', 'warning');
try {
// 先发送OPTIONS预检请求
log(' 发送OPTIONS预检请求...', 'warning');
const optionsResponse = await fetch(`${API_BASE}/api/stores`, {
method: 'OPTIONS',
headers: {
'Origin': 'http://localhost:5174',
'Access-Control-Request-Method': 'GET',
'Access-Control-Request-Headers': 'content-type'
}
});
log(` OPTIONS响应: ${optionsResponse.status}`, optionsResponse.ok ? 'success' : 'error');
// 发送实际请求
log(' 发送GET请求...', 'warning');
const response = await fetch(`${API_BASE}/api/stores`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'cors'
});
if (response.ok) {
const data = await response.json();
log(`✅ /api/stores请求成功返回${data.data?.length || 0}个店铺`, 'success');
} else {
const errorText = await response.text();
log(`❌ /api/stores失败: HTTP ${response.status}`, 'error');
log(` 错误详情: ${errorText}`, 'error');
}
} catch (error) {
log(`❌ /api/stores CORS错误: ${error.message}`, 'error');
}
}
async function testAllAPIs() {
log('🔗 测试所有API端点...', 'warning');
const endpoints = [
'/api/health',
'/api/stores',
'/api/products',
'/api/training',
'/api/cors-test'
];
for (const endpoint of endpoints) {
try {
const response = await fetch(`${API_BASE}${endpoint}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'cors'
});
if (response.ok) {
log(`✅ ${endpoint} - 成功 (${response.status})`, 'success');
} else {
log(`❌ ${endpoint} - 失败 (${response.status})`, 'error');
}
} catch (error) {
log(`❌ ${endpoint} - CORS错误: ${error.message}`, 'error');
}
}
}
// 页面加载时的提示
window.onload = function() {
log('📝 CORS测试页面已加载', 'warning');
log(`🎯 测试目标: ${API_BASE}`, 'warning');
log('💡 点击按钮开始测试,同时打开浏览器开发者工具查看网络请求', 'warning');
// 如果页面不是从localhost:5174访问给出警告
if (!window.location.href.includes('localhost:5174')) {
log('⚠️ 注意当前页面不是从localhost:5174访问可能无法完全模拟前端环境', 'error');
log('💡 建议将此文件复制到前端项目的public目录然后从http://localhost:5174访问', 'warning');
}
};
</script>
</body>
</html>