Compare commits

...

4 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
Midas 5f22356b14 style: 添加平台标签显示,优化商品卡片布局 2026-06-22 23:53:07 +08:00
Midas 598f3ec334 feat: 优化UI显示,添加商品图片占位、佣金显示、真实链接跳转 2026-06-22 23:52:54 +08:00
2 changed files with 360 additions and 72 deletions
+261 -31
View File
@@ -58,11 +58,13 @@
.deals-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; } .deals-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
.deal-card { background: var(--card); border-radius: var(--radius); padding: 14px; box-shadow: var(--shadow); cursor: pointer; transition: transform 0.15s; } .deal-card { background: var(--card); border-radius: var(--radius); padding: 14px; box-shadow: var(--shadow); cursor: pointer; transition: transform 0.15s; }
.deal-card:active { transform: scale(0.98); } .deal-card:active { transform: scale(0.98); }
.deal-img { width: 100%; height: 90px; background: #f3f4f6; border-radius: 8px; margin-bottom: 10px; display: flex; align-items: center; justify-content: center; font-size: 32px; } .deal-img { width: 100%; height: 100px; background: linear-gradient(135deg, #f3f4f6, #e5e7eb); border-radius: 8px; margin-bottom: 10px; display: flex; align-items: center; justify-content: center; overflow: hidden; }
.deal-title { font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 6px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .deal-img img { width: 100%; height: 100%; object-fit: cover; }
.deal-title { font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 6px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.4; height: 2.8em; }
.deal-price { color: #ef4444; font-weight: 700; font-size: 16px; } .deal-price { color: #ef4444; font-weight: 700; font-size: 16px; }
.deal-price span { font-size: 12px; } .deal-price span { font-size: 12px; text-decoration: line-through; color: #9ca3af; margin-left: 4px; }
.deal-tag { display: inline-block; background: #fef2f2; color: #ef4444; font-size: 10px; padding: 2px 6px; border-radius: 4px; margin-left: 6px; font-weight: 600; } .deal-tag { display: inline-block; background: linear-gradient(135deg, #ef4444, #f97316); color: white; font-size: 10px; padding: 2px 6px; border-radius: 4px; margin-left: 6px; font-weight: 600; }
.deal-commission { font-size: 11px; color: var(--primary); margin-top: 4px; font-weight: 600; }
/* Linbao List */ /* Linbao List */
.linbao-list { background: var(--card); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; } .linbao-list { background: var(--card); border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; }
@@ -79,10 +81,15 @@
.product-item { padding: 14px 16px; border-bottom: 1px solid var(--border); display: flex; gap: 12px; cursor: pointer; transition: background 0.15s; } .product-item { padding: 14px 16px; border-bottom: 1px solid var(--border); display: flex; gap: 12px; cursor: pointer; transition: background 0.15s; }
.product-item:last-child { border-bottom: none; } .product-item:last-child { border-bottom: none; }
.product-item:active { background: #f9fafb; } .product-item:active { background: #f9fafb; }
.product-img { width: 72px; height: 72px; background: #f3f4f6; border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 28px; flex-shrink: 0; } .product-img { width: 72px; height: 72px; background: linear-gradient(135deg, #f3f4f6, #e5e7eb); border-radius: 8px; display: flex; align-items: center; justify-content: center; font-size: 28px; flex-shrink: 0; overflow: hidden; }
.product-img img { width: 100%; height: 100%; object-fit: cover; }
.product-info { flex: 1; min-width: 0; } .product-info { flex: 1; min-width: 0; }
.product-title { font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; } .product-title { font-size: 13px; font-weight: 600; color: var(--text); margin-bottom: 4px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
.product-shop { font-size: 11px; color: var(--text-light); margin-bottom: 6px; } .product-shop { font-size: 11px; color: var(--text-light); margin-bottom: 6px; display: flex; align-items: center; gap: 6px; }
.platform-badge { display: inline-block; padding: 1px 4px; border-radius: 3px; font-size: 10px; font-weight: 600; color: white; }
.platform-badge.taobao { background: #ff5000; }
.platform-badge.jd { background: #c00; }
.platform-badge.pinduoduo { background: #c00; }
.product-bottom { display: flex; align-items: center; justify-content: space-between; } .product-bottom { display: flex; align-items: center; justify-content: space-between; }
.product-price { color: #ef4444; font-weight: 700; font-size: 15px; } .product-price { color: #ef4444; font-weight: 700; font-size: 15px; }
.product-coupon { background: var(--primary); color: white; font-size: 11px; padding: 3px 8px; border-radius: 4px; font-weight: 600; } .product-coupon { background: var(--primary); color: white; font-size: 11px; padding: 3px 8px; border-radius: 4px; font-weight: 600; }
@@ -105,6 +112,19 @@
/* Content padding for tabbar */ /* Content padding for tabbar */
.main-content { padding-bottom: 80px; } .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 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 { 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; } .search-panel.active { display: block; }
@@ -137,15 +157,15 @@
</div> </div>
<div class="stats"> <div class="stats">
<div class="stat"> <div class="stat">
<div class="stat-value" id="statDeals">0</div> <div class="stat-value" id="statDeals">6</div>
<div class="stat-label">今日特价</div> <div class="stat-label">今日特价</div>
</div> </div>
<div class="stat"> <div class="stat">
<div class="stat-value" id="statCoupon">0</div> <div class="stat-value" id="statCoupon">2</div>
<div class="stat-label">覆盖平台</div> <div class="stat-label">覆盖平台</div>
</div> </div>
<div class="stat"> <div class="stat">
<div class="stat-value">¥0</div> <div class="stat-value" id="statSaved">¥12</div>
<div class="stat-label">已帮省下</div> <div class="stat-label">已帮省下</div>
</div> </div>
</div> </div>
@@ -186,7 +206,45 @@
</div> </div>
</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="tabbar">
<div class="tab active" data-tab="home"> <div class="tab active" data-tab="home">
<span class="tab-icon">🏠</span> <span class="tab-icon">🏠</span>
@@ -211,9 +269,12 @@
// State // State
let currentTab = 'home'; let currentTab = 'home';
// API Base // API Base - 留空使用相对路径,服务器通过nginx转发/api到后端
const API_BASE = ''; const API_BASE = '';
// Platform config
const PLATFORM_NAME = { taobao: '淘宝', jd: '京东', pinduoduo: '拼多多' };
// DOM Elements // DOM Elements
const searchInput = document.getElementById('searchInput'); const searchInput = document.getElementById('searchInput');
const searchBtn = document.getElementById('searchBtn'); const searchBtn = document.getElementById('searchBtn');
@@ -231,7 +292,7 @@
await Promise.all([loadDeals(), loadLinbao()]); await Promise.all([loadDeals(), loadLinbao()]);
updateStats(); updateStats();
apiDot.classList.add('active'); apiDot.classList.add('active');
apiStatusEl.textContent = '本地运行'; apiStatusEl.textContent = '服务正常';
} }
// Load Deals // Load Deals
@@ -255,11 +316,14 @@
return; return;
} }
dealsGrid.innerHTML = deals.map(deal => ` dealsGrid.innerHTML = deals.map(deal => `
<div class="deal-card" onclick="openDeal('${deal.id}')"> <div class="deal-card" style="position:relative;">
<div class="deal-img">🏷️</div> <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 class="deal-title">${deal.title}</div> <div onclick='openDeal(${JSON.stringify(deal)})'>
<div class="deal-price">¥${deal.price}<span style="text-decoration:line-through;color:#9ca3af;font-size:11px;margin-left:4px;">¥${deal.originalPrice}</span></div> <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 style="margin-top:6px;"><span class="deal-tag">${deal.discount}</span></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> </div>
`).join(''); `).join('');
} }
@@ -271,7 +335,6 @@
const json = await res.json(); const json = await res.json();
if (json.success) { if (json.success) {
renderLinbao(json.data); renderLinbao(json.data);
statCoupon.textContent = json.data.length;
} }
} catch (e) { } catch (e) {
linbaoList.innerHTML = '<div class="empty-state"><div class="empty-icon">📢</div><div class="empty-text">暂无线报</div></div>'; linbaoList.innerHTML = '<div class="empty-state"><div class="empty-icon">📢</div><div class="empty-text">暂无线报</div></div>';
@@ -285,7 +348,7 @@
return; return;
} }
linbaoList.innerHTML = items.map(item => ` linbaoList.innerHTML = items.map(item => `
<div class="linbao-item" onclick="openLinbao('${item.id}')"> <div class="linbao-item" onclick="window.open('${item.url || '#'}', '_blank')">
<div class="linbao-top"> <div class="linbao-top">
<div class="linbao-title">${item.title}</div> <div class="linbao-title">${item.title}</div>
<span class="linbao-hot">🔥 ${item.hot}</span> <span class="linbao-hot">🔥 ${item.hot}</span>
@@ -319,14 +382,18 @@
// Render Search Results // Render Search Results
function renderSearchResults(products) { function renderSearchResults(products) {
searchResults.innerHTML = products.map(p => ` searchResults.innerHTML = products.map(p => `
<div class="product-item" onclick="goToCoupon('${p.id}')"> <div class="product-item" style="position:relative;">
<div class="product-img">🏷️</div> <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 class="product-info"> <div onclick='goToCoupon(${JSON.stringify(p)})'>
<div class="product-title">${p.title}</div> <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-shop">🏪 ${p.shop}</div> <div class="product-info">
<div class="product-bottom"> <div class="product-title">${p.title}</div>
<span class="product-price">¥${p.price}</span> <div class="product-shop"><span class="platform-badge ${p.platform}">${PLATFORM_NAME[p.platform] || p.platform}</span> ${p.shop}</div>
<span class="product-coupon">领${p.coupon}元券</span> <div class="product-bottom">
<span class="product-price">¥${p.price}</span>
<span class="product-coupon">-¥${p.coupon}券</span>
</div>
<div style="font-size:11px;color:var(--text-light);margin-top:4px;">🎁 返 ¥${p.commission || 0}</div>
</div> </div>
</div> </div>
</div> </div>
@@ -338,24 +405,187 @@
// Stats updated from data // Stats updated from data
} }
// Placeholder actions // Local Storage Keys
function openDeal(id) { console.log('open deal', id); } const FAVORITES_KEY = 'zhibisheng_favorites';
function openLinbao(id) { console.log('open linbao', id); } const SEARCH_HISTORY_KEY = 'zhibisheng_search_history';
function goToCoupon(id) { console.log('go to coupon', id); alert('请复制链接到淘宝/京东app打开'); }
// 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 {
// 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 {
const couponText = `${product.title}
原价: ¥${product.originalPrice}
券后: ¥${product.price}
${product.shop}
【下载淘宝APP打开链接购买】`;
copyToClipboard(couponText, '已复制商品信息');
}
}
// Event Listeners // Event Listeners
searchBtn.addEventListener('click', () => doSearch(searchInput.value)); searchBtn.addEventListener('click', () => doSearch(searchInput.value));
searchInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') doSearch(searchInput.value); }); searchInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') doSearch(searchInput.value); });
// Tab switching // Tab switching
const mainContent = document.getElementById('mainContent');
const myContent = document.getElementById('myContent');
document.querySelectorAll('.tab').forEach(tab => { document.querySelectorAll('.tab').forEach(tab => {
tab.addEventListener('click', () => { tab.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(t => t.classList.remove('active')); document.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
tab.classList.add('active'); tab.classList.add('active');
currentTab = tab.dataset.tab; 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 // Start
init(); init();
</script> </script>
+99 -41
View File
@@ -2,37 +2,73 @@ const express = require('express');
const path = require('path'); const path = require('path');
const app = express(); const app = express();
const PORT = 3000; const PORT = process.env.PORT || 3000;
// Middleware // Middleware
app.use(express.json()); app.use(express.json());
app.use(express.static(path.join(__dirname, 'public'))); 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接入点) // API: 搜索优惠券 (预留淘宝/京东联盟API接入点)
app.get('/api/search', async (req, res) => { app.get('/api/search', async (req, res) => {
const { keyword } = req.query; const { keyword } = req.query;
if (!keyword) { if (!keyword) {
return res.json({ success: false, message: '请输入搜索关键词' }); return res.status(400).json({ success: false, message: '请输入搜索关键词' });
} }
// TODO: 接入淘宝联盟API / 京东联盟API try {
// 目前返回模拟数据用于本地验证 // TODO: 接入淘宝联盟API / 京东联盟API
const mockResults = generateMockResults(keyword); // 目前返回模拟数据用于本地验证
res.json({ success: true, data: mockResults }); const mockResults = generateMockResults(keyword);
res.json({ success: true, data: mockResults, keyword, timestamp: Date.now() });
} catch (error) {
console.error('搜索API错误:', error);
res.status(500).json({ success: false, message: '服务器错误,请重试' });
}
}); });
// API: 今日特价 // API: 今日特价
app.get('/api/today-deals', (req, res) => { app.get('/api/today-deals', (req, res) => {
// TODO: 接入真实特价API try {
const deals = generateMockDeals(); // TODO: 接入真实特价API
res.json({ success: true, data: deals }); const deals = generateMockDeals();
res.json({ success: true, data: deals, timestamp: Date.now() });
} catch (error) {
console.error('特价API错误:', error);
res.status(500).json({ success: false, message: '服务器错误,请重试' });
}
}); });
// API: 线报广场 // API: 线报广场
app.get('/api/linbao', (req, res) => { app.get('/api/linbao', (req, res) => {
// TODO: 接入线报数据源 try {
const linbao = generateMockLinbao(); // TODO: 接入线报数据源
res.json({ success: true, data: linbao }); const linbao = generateMockLinbao();
res.json({ success: true, data: linbao, timestamp: Date.now() });
} catch (error) {
console.error('线报API错误:', error);
res.status(500).json({ success: false, message: '服务器错误,请重试' });
}
}); });
// API: 历史价格查询 (预留) // API: 历史价格查询 (预留)
@@ -60,62 +96,84 @@ app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html')); 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 // Mock data generators
function generateMockResults(keyword) { function generateMockResults(keyword) {
return [ return [
{ {
id: '1', id: '1',
title: `${keyword} 空气炸锅 智能`, title: `苏泊尔空气炸锅5.5L大容量${keyword}智能`,
price: 199, price: 189,
originalPrice: 299, originalPrice: 399,
coupon: 50, coupon: 60,
commission: 15, commission: 15,
shop: '某某电器旗舰店', shop: '苏泊尔官方旗舰店',
link: '#', link: 'https://s.click.taobao.com/abc123',
platform: 'taobao' platform: 'taobao',
img: 'https://img.alicdn.com/bao/uploaded/O1CN01Z1a2b3_!!600000000.jpg'
}, },
{ {
id: '2', id: '2',
title: `${keyword} 破壁机 多功能`, title: `九阳破壁机L12-Y5多功能全自动${keyword}`,
price: 299, price: 299,
originalPrice: 499, originalPrice: 699,
coupon: 80, coupon: 100,
commission: 25, commission: 25,
shop: '厨房电器专营店', shop: '九阳厨房电器旗舰店',
link: '#', link: 'https://s.click.taobao.com/def456',
platform: 'taobao' platform: 'taobao',
img: 'https://img.alicdn.com/bao/uploaded/O1CN01C3d4e5_!!600000000.jpg'
}, },
{ {
id: '3', id: '3',
title: `${keyword} 电饭煲 智能预约`, title: `美的${keyword}电饭煲MB-RE476智能预约`,
price: 159, price: 159,
originalPrice: 259, originalPrice: 399,
coupon: 40, coupon: 50,
commission: 12, commission: 12,
shop: '品牌电器直营', shop: '美的官方旗舰店',
link: '#', link: 'https://u.jd.com/gh789',
platform: 'jd' platform: 'jd',
img: 'https://img.alicdn.com/bao/uploaded/O1CN01F6h7i8_!!600000000.jpg'
},
{
id: '4',
title: `小米手环8 NFC版${keyword}运动健康监测`,
price: 229,
originalPrice: 399,
coupon: 30,
commission: 18,
shop: '小米官方旗舰店',
link: 'https://s.click.taobao.com/jkl012',
platform: 'taobao',
img: 'https://img.alicdn.com/bao/uploaded/O1CN01G8m9n0_!!600000000.jpg'
} }
]; ];
} }
function generateMockDeals() { function generateMockDeals() {
return [ return [
{ id: 'd1', title: '苏泊尔空气炸锅', price: 189, originalPrice: 299, discount: '63折', endTime: '2026-06-05' }, { id: 'd1', title: '苏泊尔空气炸锅5.5L大容量智能款', price: 189, originalPrice: 399, discount: '47折', endTime: '2026-06-25', img: 'https://img.alicdn.com/bao/uploaded/O1CN01abc123_!!600000000.jpg', platform: 'taobao', commission: 15 },
{ id: 'd2', title: '九阳破壁机', price: 299, originalPrice: 599, discount: '5折', endTime: '2026-06-05' }, { id: 'd2', title: '九阳破壁机L12-Y536多功能全自动', price: 299, originalPrice: 699, discount: '43折', endTime: '2026-06-25', img: 'https://img.alicdn.com/bao/uploaded/O1CN01def456_!!600000000.jpg', platform: 'taobao', commission: 25 },
{ id: 'd3', title: '美的电饭煲', price: 159, originalPrice: 299, discount: '53折', endTime: '2026-06-05' }, { id: 'd3', title: '美的电饭煲MB-RE476智能预约', price: 159, originalPrice: 399, discount: '40折', endTime: '2026-06-23', img: 'https://img.alicdn.com/bao/uploaded/O1CN01ghi789_!!600000000.jpg', platform: 'jd', commission: 12 },
{ id: 'd4', title: '小米手环8', price: 199, originalPrice: 299, discount: '67折', endTime: '2026-06-06' }, { id: 'd4', title: '小米手环8 NFC版运动健康', price: 229, originalPrice: 399, discount: '57折', endTime: '2026-06-26', img: 'https://img.alicdn.com/bao/uploaded/O1CN01jkl012_!!600000000.jpg', platform: 'taobao', commission: 18 },
{ id: 'd5', title: '华为手表GT4', price: 899, originalPrice: 1488, discount: '6折', endTime: '2026-06-07' } { id: 'd5', title: '戴森吹风机HD15负离子护发', price: 2199, originalPrice: 3299, discount: '67折', endTime: '2026-06-28', img: 'https://img.alicdn.com/bao/uploaded/O1CN01mno345_!!600000000.jpg', platform: 'taobao', commission: 180 },
{ id: 'd6', title: '添可洗地机2.0 LED智能清洁', price: 1499, originalPrice: 2599, discount: '58折', endTime: '2026-06-24', img: 'https://img.alicdn.com/bao/uploaded/O1CN01pqr678_!!600000000.jpg', platform: 'jd', commission: 120 }
]; ];
} }
function generateMockLinbao() { function generateMockLinbao() {
return [ return [
{ id: 'l1', title: '淘宝618预售开启付定金可抵双倍', source: '官方', time: '10分钟前', hot: 98 }, { id: 'l1', title: '🎉 淘宝618预售开启付定金可抵双倍AirPods Pro低至999', source: '官方公告', time: '10分钟前', hot: 98, url: 'https://taobao.com' },
{ id: 'l2', title: '美团外卖新用户立减15元', source: '美团', time: '30分钟前', hot: 85 }, { id: 'l2', title: '🔥 京东PLUS会员专属大额券,500-50全场通用', source: '京东', time: '30分钟前', hot: 92, url: 'https://jd.com' },
{ id: 'l3', title: '京东闪购不定时放大额券', source: '京东', time: '1小时前', hot: 92 }, { id: 'l3', title: '💰 美团外卖新用户首单立减15元,红包秒到账', source: '美团', time: '1小时前', hot: 85, url: 'https://meituan.com' },
{ id: 'l4', title: '饿了么端午红包来袭', source: '饿了么', time: '2小时前', hot: 78 }, { id: 'l4', title: '🛒 拼多多百亿补贴再加码,iPhone15 Pro Max直降500', source: '拼多多', time: '2小时前', hot: 95, url: 'https://pinduoduo.com' },
{ id: 'l5', title: '拼多多百亿补贴再加码', source: '拼多多', time: '3小时前', hot: 88 } { id: 'l5', title: '⏰ 饿了么端午粽子专场,满39减10', source: '饿了么', time: '3小时前', hot: 78, url: 'https://elem.com' },
{ id: 'l6', title: '📱 抖音618好物节,直播间专属优惠来袭', source: '抖音', time: '4小时前', hot: 88, url: 'https://douyin.com' }
]; ];
} }