Repository navigation
Expand file tree
/
Copy pathdebug_test.html
More file actions
94 lines (82 loc) · 3.5 KB
/
Copy pathdebug_test.html
File metadata and controls
94 lines (82 loc) · 3.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>完整测试</title>
<style>
.news-card { background: #f5f5f5; padding: 15px; margin: 10px 0; border-radius: 8px; }
.error { color: red; }
.loading { color: blue; }
</style>
</head>
<body>
<h1>NewsTimeline 前端逻辑测试</h1>
<div id="newsFeed" class="loading">正在加载新闻...</div>
<div id="newsCount"></div>
<script>
const API_BASE = 'https://newstimeline-api.onrender.com';
const SAMPLE_NEWS = [
{id: 1, title: '示例新闻1', sourceName: '测试来源', category: '科技'},
{id: 2, title: '示例新闻2', sourceName: '测试来源', category: '财经'},
];
let state = {
newsPage: 1,
currentCategory: '全部',
allNews: []
};
async function api(endpoint, params = {}) {
try {
const url = new URL(API_BASE + endpoint);
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
console.log('请求URL:', url.toString());
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
const resp = await fetch(url, { signal: controller.signal });
clearTimeout(timeoutId);
const data = await resp.json();
console.log('API响应:', data);
return data;
} catch (e) {
console.error('API错误:', e);
return { code: 500, message: e.message };
}
}
async function loadNews() {
const feed = document.getElementById('newsFeed');
feed.innerHTML = '<div class="loading">正在加载新闻...</div>';
feed.style.color = 'blue';
const resp = await api('/api/news', { category: state.currentCategory, page: state.newsPage, limit: 20 });
console.log('loadNews resp:', resp);
// 兼容两种API格式
let news = [];
if (resp.news) {
news = resp.news;
} else if (resp.data) {
news = resp.data;
}
console.log('解析后的news:', news);
if (news && news.length > 0) {
feed.style.color = 'black';
feed.innerHTML = '';
news.forEach(item => {
const html = '<div class="news-card">' +
'<strong>' + item.title + '</strong>' +
'<br>来源: ' + (item.sourceName || item.source || '未知') +
'<br>时间: ' + (item.pubDate || item.published || '') +
'</div>';
feed.insertAdjacentHTML('beforeend', html);
});
document.getElementById('newsCount').textContent = '共 ' + (resp.total || news.length) + ' 条';
} else {
feed.innerHTML = '<div class="error">API返回空数据,使用示例</div>';
feed.style.color = 'red';
SAMPLE_NEWS.forEach(item => {
feed.insertAdjacentHTML('beforeend', '<div class="news-card">' + item.title + '</div>');
});
}
}
// 启动
loadNews();
</script>
</body>
</html>