Compare commits

...

2 Commits

Author SHA1 Message Date
Midas b7093816f0 feat: 优化API错误处理、CORS支持、请求日志、404处理
- 添加CORS headers支持跨域访问
- 添加请求日志记录
- 改善各API的错误处理
- 添加404处理器
- 添加timestamp返回便于调试
2026-06-23 22:53:14 +08:00
Midas 62e92a08bc feat: 添加收藏功能、搜索历史、复制功能,优化用户体验 2026-06-22 23:54:51 +08:00
2 changed files with 279 additions and 29 deletions
+214 -5
View File
@@ -112,6 +112,19 @@
/* Content padding for tabbar */
.main-content { padding-bottom: 80px; }
/* My Content */
.my-content { padding-bottom: 80px; }
.fav-item, .history-item { background: var(--card); border-radius: var(--radius); padding: 12px; margin-bottom: 8px; display: flex; gap: 10px; align-items: center; box-shadow: var(--shadow); }
.fav-img { width: 48px; height: 48px; border-radius: 6px; background: #f3f4f6; display: flex; align-items: center; justify-content: center; overflow: hidden; flex-shrink: 0; }
.fav-img img { width: 100%; height: 100%; object-fit: cover; }
.fav-info { flex: 1; min-width: 0; }
.fav-title { font-size: 13px; font-weight: 600; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; overflow: hidden; }
.fav-price { font-size: 14px; color: #ef4444; font-weight: 700; }
.fav-remove { color: var(--text-light); font-size: 18px; padding: 4px 8px; cursor: pointer; }
.history-item { justify-content: space-between; }
.history-keyword { font-size: 14px; }
.history-time { font-size: 11px; color: var(--text-light); }
/* Search Results Panel */
.search-panel { display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: var(--bg); z-index: 100; overflow-y: auto; }
.search-panel.active { display: block; }
@@ -193,7 +206,45 @@
</div>
</div>
<!-- Tab Bar -->
<!-- My Tab Content -->
<div class="my-content" id="myContent" style="display:none;padding:20px;">
<div style="text-align:center;margin-bottom:24px;">
<div style="font-size:48px;margin-bottom:8px;">👤</div>
<div style="font-size:18px;font-weight:700;color:var(--text);">智币省用户</div>
<div style="font-size:13px;color:var(--text-light);">开始省钱之旅吧 ~</div>
</div>
<!-- Stats -->
<div style="display:flex;gap:12px;margin-bottom:24px;">
<div style="flex:1;background:var(--card);border-radius:12px;padding:16px;text-align:center;box-shadow:var(--shadow);">
<div style="font-size:24px;font-weight:700;color:var(--primary);" id="myFavCount">0</div>
<div style="font-size:12px;color:var(--text-light);">我的收藏</div>
</div>
<div style="flex:1;background:var(--card);border-radius:12px;padding:16px;text-align:center;box-shadow:var(--shadow);">
<div style="font-size:24px;font-weight:700;color:#f59e0b;" id="mySearchCount">0</div>
<div style="font-size:12px;color:var(--text-light);">搜索记录</div>
</div>
</div>
<!-- Favorites -->
<div style="margin-bottom:24px;">
<div style="font-size:16px;font-weight:700;margin-bottom:12px;">❤️ 我的收藏</div>
<div id="favoritesList">
<div style="text-align:center;padding:20px;color:var(--text-light);font-size:14px;">暂无收藏</div>
</div>
</div>
<!-- Search History -->
<div>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
<div style="font-size:16px;font-weight:700;">🔍 搜索记录</div>
<div style="font-size:12px;color:var(--text-light);cursor:pointer;" onclick="clearSearchHistory()">清空</div>
</div>
<div id="searchHistoryList">
<div style="text-align:center;padding:20px;color:var(--text-light);font-size:14px;">暂无搜索记录</div>
</div>
</div>
</div>
<div class="tabbar">
<div class="tab active" data-tab="home">
<span class="tab-icon">🏠</span>
@@ -265,12 +316,15 @@
return;
}
dealsGrid.innerHTML = deals.map(deal => `
<div class="deal-card" onclick='openDeal(${JSON.stringify(deal)})'>
<div class="deal-card" style="position:relative;">
<div class="fav-btn" onclick="event.stopPropagation();toggleFavorite(${JSON.stringify(deal)},'deal')" style="position:absolute;top:8px;right:8px;font-size:18px;cursor:pointer;z-index:2;">${isFavorited('deal_'+deal.id) ? '❤️' : '🤍'}</div>
<div onclick='openDeal(${JSON.stringify(deal)})'>
<div class="deal-img"><img src="https://picsum.photos/seed/${deal.id}/200/200" alt="${deal.title}" loading="lazy" onerror="this.style.display='none'"></div>
<div class="deal-title" style="margin-top:4px;"><span class="platform-badge ${deal.platform}" style="font-size:9px;margin-right:4px;">${PLATFORM_NAME[deal.platform] || deal.platform}</span>${deal.title}</div>
<div class="deal-price">¥${deal.price}<span>¥${deal.originalPrice}</span><span class="deal-tag">${deal.discount}</span></div>
<div class="deal-commission">🎁 预估返 ¥${deal.commission || 0}</div>
</div>
</div>
`).join('');
}
@@ -328,7 +382,9 @@
// Render Search Results
function renderSearchResults(products) {
searchResults.innerHTML = products.map(p => `
<div class="product-item" onclick='goToCoupon(${JSON.stringify(p)})'>
<div class="product-item" style="position:relative;">
<div class="fav-btn" onclick="event.stopPropagation();toggleFavorite(${JSON.stringify(p)},'product')" style="position:absolute;top:8px;right:8px;font-size:16px;cursor:pointer;z-index:2;">${isFavorited('product_'+p.id) ? '❤️' : '🤍'}</div>
<div onclick='goToCoupon(${JSON.stringify(p)})'>
<div class="product-img"><img src="https://picsum.photos/seed/${p.id}/200/200" alt="${p.title}" loading="lazy" onerror="this.parentElement.innerHTML='🏷️'"></div>
<div class="product-info">
<div class="product-title">${p.title}</div>
@@ -340,6 +396,7 @@
<div style="font-size:11px;color:var(--text-light);margin-top:4px;">🎁 返 ¥${p.commission || 0}</div>
</div>
</div>
</div>
`).join('');
}
@@ -348,19 +405,91 @@
// Stats updated from data
}
// Local Storage Keys
const FAVORITES_KEY = 'zhibisheng_favorites';
const SEARCH_HISTORY_KEY = 'zhibisheng_search_history';
// Load favorites from localStorage
function getFavorites() {
try {
return JSON.parse(localStorage.getItem(FAVORITES_KEY) || '[]');
} catch { return []; }
}
// Save to favorites
function toggleFavorite(item, type) {
let favorites = getFavorites();
const id = type + '_' + item.id;
const index = favorites.findIndex(f => f.id === id);
if (index > -1) {
favorites.splice(index, 1);
showToast('已取消收藏');
} else {
favorites.unshift({ ...item, id, type, addedAt: Date.now() });
showToast('已收藏 ~');
}
localStorage.setItem(FAVORITES_KEY, JSON.stringify(favorites));
renderMyTab();
}
// Check if favorited
function isFavorited(id) {
return getFavorites().some(f => f.id === id);
}
// Toast notification
function showToast(msg) {
const existing = document.querySelector('.toast');
if (existing) existing.remove();
const toast = document.createElement('div');
toast.className = 'toast';
toast.textContent = msg;
toast.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:rgba(0,0,0,0.75);color:white;padding:12px 24px;border-radius:8px;font-size:14px;z-index:9999;animation:fadeIn 0.3s';
document.body.appendChild(toast);
setTimeout(() => { toast.style.opacity = '0'; setTimeout(() => toast.remove(), 300); }, 1500);
}
// Copy text to clipboard
function copyToClipboard(text, successMsg) {
if (navigator.clipboard) {
navigator.clipboard.writeText(text).then(() => showToast(successMsg || '已复制')).catch(() => fallbackCopy(text));
} else {
fallbackCopy(text);
}
}
function fallbackCopy(text) {
const ta = document.createElement('textarea');
ta.value = text;
ta.style.position = 'fixed'; ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
showToast('已复制');
}
// Actions
function openDeal(deal) {
if (deal.link && deal.link !== '#') {
window.open(deal.link, '_blank');
} else {
alert('复制商品链接,请在淘宝/京东App打开购买~');
// Generate mock coupon link
const couponLink = `https://taobao.com/item?id=${deal.id}`;
copyToClipboard(couponLink, '链接已复制,打开淘宝购买');
}
}
function goToCoupon(product) {
if (product.link && product.link !== '#') {
window.open(product.link, '_blank');
} else {
alert('复制商品链接,请在淘宝/京东App打开购买~');
const couponText = `${product.title}
原价: ¥${product.originalPrice}
券后: ¥${product.price}
${product.shop}
【下载淘宝APP打开链接购买】`;
copyToClipboard(couponText, '已复制商品信息');
}
}
@@ -369,14 +498,94 @@
searchInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') doSearch(searchInput.value); });
// Tab switching
const mainContent = document.getElementById('mainContent');
const myContent = document.getElementById('myContent');
document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active');
currentTab = tab.dataset.tab;
if (currentTab === 'my') {
mainContent.style.display = 'none';
myContent.style.display = 'block';
renderMyTab();
} else {
mainContent.style.display = 'block';
myContent.style.display = 'none';
}
});
});
// Render My Tab
function renderMyTab() {
const favorites = getFavorites();
document.getElementById('myFavCount').textContent = favorites.length;
// Render favorites
if (favorites.length === 0) {
document.getElementById('favoritesList').innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-light);font-size:14px;">暂无收藏</div>';
} else {
document.getElementById('favoritesList').innerHTML = favorites.map(f => `
<div class="fav-item">
<div class="fav-img"><img src="https://picsum.photos/seed/${f.id}/100/100" alt=""></div>
<div class="fav-info">
<div class="fav-title">${f.title}</div>
<div class="fav-price">¥${f.price}</div>
</div>
<div class="fav-remove" onclick="toggleFavorite({id:'${f.id.replace(f.type+'_', '')}', title:'${f.title}', price:${f.price}}, '${f.type}')">✕</div>
</div>
`).join('');
}
// Render search history
try {
const history = JSON.parse(localStorage.getItem(SEARCH_HISTORY_KEY) || '[]');
document.getElementById('mySearchCount').textContent = history.length;
if (history.length === 0) {
document.getElementById('searchHistoryList').innerHTML = '<div style="text-align:center;padding:20px;color:var(--text-light);font-size:14px;">暂无搜索记录</div>';
} else {
document.getElementById('searchHistoryList').innerHTML = history.slice(0, 10).map(h => `
<div class="history-item" onclick="searchFromHistory('${h.keyword}')">
<span class="history-keyword">🔍 ${h.keyword}</span>
<span class="history-time">${formatTime(h.time)}</span>
</div>
`).join('');
}
} catch {}
}
function formatTime(ts) {
const d = new Date(ts);
return `${d.getMonth()+1}/${d.getDate()} ${d.getHours()}:${String(d.getMinutes()).padStart(2, '0')}`;
}
function searchFromHistory(keyword) {
searchInput.value = keyword;
document.querySelector('[data-tab="home"]').click();
doSearch(keyword);
}
function clearSearchHistory() {
localStorage.removeItem(SEARCH_HISTORY_KEY);
renderMyTab();
showToast('已清空');
}
// Save search to history
const originalDoSearch = doSearch;
async function doSearch(keyword) {
if (!keyword.trim()) return;
try {
const history = JSON.parse(localStorage.getItem(SEARCH_HISTORY_KEY) || '[]');
const filtered = history.filter(h => h.keyword !== keyword);
filtered.unshift({ keyword, time: Date.now() });
localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(filtered.slice(0, 20)));
} catch {}
return originalDoSearch(keyword);
}
// Start
init();
</script>
+46 -5
View File
@@ -2,37 +2,73 @@ const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;
const PORT = process.env.PORT || 3000;
// Middleware
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
// CORS headers
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
if (req.method === 'OPTIONS') {
return res.sendStatus(200);
}
next();
});
// Request logging
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(`${req.method} ${req.path} - ${res.statusCode} (${duration}ms)`);
});
next();
});
// API: 搜索优惠券 (预留淘宝/京东联盟API接入点)
app.get('/api/search', async (req, res) => {
const { keyword } = req.query;
if (!keyword) {
return res.json({ success: false, message: '请输入搜索关键词' });
return res.status(400).json({ success: false, message: '请输入搜索关键词' });
}
try {
// TODO: 接入淘宝联盟API / 京东联盟API
// 目前返回模拟数据用于本地验证
const mockResults = generateMockResults(keyword);
res.json({ success: true, data: mockResults });
res.json({ success: true, data: mockResults, keyword, timestamp: Date.now() });
} catch (error) {
console.error('搜索API错误:', error);
res.status(500).json({ success: false, message: '服务器错误,请重试' });
}
});
// API: 今日特价
app.get('/api/today-deals', (req, res) => {
try {
// TODO: 接入真实特价API
const deals = generateMockDeals();
res.json({ success: true, data: deals });
res.json({ success: true, data: deals, timestamp: Date.now() });
} catch (error) {
console.error('特价API错误:', error);
res.status(500).json({ success: false, message: '服务器错误,请重试' });
}
});
// API: 线报广场
app.get('/api/linbao', (req, res) => {
try {
// TODO: 接入线报数据源
const linbao = generateMockLinbao();
res.json({ success: true, data: linbao });
res.json({ success: true, data: linbao, timestamp: Date.now() });
} catch (error) {
console.error('线报API错误:', error);
res.status(500).json({ success: false, message: '服务器错误,请重试' });
}
});
// API: 历史价格查询 (预留)
@@ -60,6 +96,11 @@ app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ success: false, message: 'API不存在' });
});
// Mock data generators
function generateMockResults(keyword) {
return [