酷代码 AI
菜单
服务商
DeepSeek字节豆包
更多选项

一键分享网站开发:支持百度QQ抖音的后端与数据库实现

好的,我将为你设计一个 **真实可用的一键分享页面**,支持 **分享到百度、QQ、抖音** 等平台,并包含 **后端(Node.js + Express)** 和 **数据库(SQLite)** 支持用户注册、分享记录存储、分享链接生成与管理。 --- ## 🛠 技术栈 - **前端**:HTML + CSS + JavaScript (纯静态页面) - **后端**:Node.js + Express - **数据库**:SQLite(无需额外安装,使用 `better-sqlite3` 或 `sql.js`) - **分享机制**:生成唯一短链接,用户访问后跳转到目标网站 --- ## 📁 项目结构 ``` one-click-share/ ├── public/ │ ├── index.html ← 分享页面前端 │ ├── style.css │ └── share.js ├── server.js ← Express 后端 ├── package.json └── share.db ← SQLite 数据库文件(自动生成) ``` --- ## 📦 安装与运行 ```bash # 1. 初始化项目 npm init -y # 2. 安装依赖 npm install express better-sqlite3 uuid # 3. 运行 node server.js ``` > 打开浏览器访问 `http://localhost:3000` 即可看到分享页面。 --- ## 🧩 后端代码 (server.js) ```javascript const express = require('express'); const Database = require('better-sqlite3'); const { v4: uuidv4 } = require('uuid'); const path = require('path'); // 数据库初始化 const db = new Database('share.db'); db.exec(` CREATE TABLE IF NOT EXISTS shares ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL, target_url TEXT NOT NULL, platform TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP, click_count INTEGER DEFAULT 0 ); CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL, created_at DATETIME DEFAULT CURRENT_TIMESTAMP ); `); const app = express(); app.use(express.json()); app.use(express.static(path.join(__dirname, 'public'))); // 用户注册 app.post('/api/register', (req, res) => { const { username, password } = req.body; if (!username || !password) { return res.status(400).json({ error: '用户名和密码不能为空' }); } try { const id = uuidv4(); db.prepare('INSERT INTO users (id, username, password) VALUES (?, ?, ?)').run(id, username, password); res.json({ success: true, userId: id }); } catch (e) { res.status(400).json({ error: '用户名已存在' }); } }); // 创建分享链接 app.post('/api/create-share', (req, res) => { const { userId, targetUrl, platform } = req.body; if (!userId || !targetUrl || !platform) { return res.status(400).json({ error: '缺少必要参数' }); } const id = uuidv4().slice(0, 8); // 短链接ID db.prepare('INSERT INTO shares (id, user_id, target_url, platform) VALUES (?, ?, ?, ?)').run(id, userId, targetUrl, platform); const shareLink = `${req.protocol}://${req.get('host')}/s/${id}`; res.json({ success: true, shareLink, id }); }); // 访问短链接(重定向) app.get('/s/:id', (req, res) => { const { id } = req.params; const row = db.prepare('SELECT * FROM shares WHERE id = ?').get(id); if (!row) { return res.status(404).send('链接不存在'); } db.prepare('UPDATE shares SET click_count = click_count + 1 WHERE id = ?').run(id); // 根据platform生成对应分享URL(模拟) const platformRedirects = { baidu: `https://tieba.baidu.com/f?kw=share`, qq: `https://connect.qq.com/widget/shareqq/index.html?url=${encodeURIComponent(row.target_url)}`, douyin: `https://www.douyin.com/share/note/${encodeURIComponent(row.target_url)}` }; const redirectUrl = platformRedirects[row.platform] || row.target_url; res.redirect(redirectUrl); }); // 查询用户分享记录 app.get('/api/user-shares/:userId', (req, res) => { const rows = db.prepare('SELECT * FROM shares WHERE user_id = ? ORDER BY created_at DESC').all(req.params.userId); res.json(rows); }); // 查询所有分享(演示用) app.get('/api/all-shares', (req, res) => { const rows = db.prepare('SELECT * FROM shares ORDER BY created_at DESC LIMIT 50').all(); res.json(rows); }); const PORT = 3000; app.listen(PORT, () => { console.log(`服务器已启动: http://localhost:${PORT}`); }); ``` --- ## 🌐 前端页面 (public/index.html) ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>一键分享页面</title> <link rel="stylesheet" href="style.css"> </head> <body> <div class="container"> <h1>📢 一键分享到各大平台</h1> <div class="card"> <h2>注册 / 登录(简化)</h2> <input type="text" id="username" placeholder="用户名" /> <input type="password" id="password" placeholder="密码" /> <button onclick="register()">注册</button> </div> <div class="card"> <h2>🌍 创建分享链接</h2> <input type="text" id="targetUrl" placeholder="输入目标网址 (如 https://你的站点)" /> <label>选择分享平台:</label> <select id="platform"> <option value="baidu">百度贴吧</option> <option value="qq">QQ</option> <option value="douyin">抖音</option> </select> <button onclick="createShare()">生成分享链接</button> <div id="shareResult"></div> </div> <div class="card"> <h2>📊 我的分享记录</h2> <div id="shareList"></div> </div> </div> <script src="share.js"></script> </body> </html> ``` --- ## 🎨 样式文件 (public/style.css) ```css * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; padding: 20px; } .container { max-width: 700px; margin: 0 auto; color: #333; } h1 { text-align: center; color: #fff; margin-bottom: 30px; font-size: 2.2rem; } .card { background: rgba(255,255,255,0.95); border-radius: 16px; padding: 25px; margin-bottom: 25px; box-shadow: 0 8px 32px rgba(0,0,0,0.1); } .card h2 { margin-bottom: 15px; color: #4a4a4a; } input, select { width: 100%; padding: 12px; margin-bottom: 12px; border: 1px solid #ddd; border-radius: 8px; font-size: 1rem; transition: border 0.3s; } input:focus, select:focus { border-color: #667eea; outline: none; } button { width: 100%; padding: 12px; background: #667eea; color: #fff; border: none; border-radius: 8px; font-size: 1rem; cursor: pointer; transition: background 0.3s; } button:hover { background: #5a67d8; } #shareResult, #shareList { margin-top: 15px; padding: 10px; background: #f9f9f9; border-radius: 8px; } #shareList div { padding: 8px; border-bottom: 1px solid #eee; } #shareList div:last-child { border-bottom: none; } ``` --- ## 📜 前端JS (public/share.js) ```javascript // 当前用户ID(简化版,生产环境请使用token) let currentUserId = null; async function register() { const username = document.getElementById('username').value.trim(); const password = document.getElementById('password').value.trim(); if (!username || !password) return alert('请填写用户名和密码'); const res = await fetch('/api/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username, password }) }); const data = await res.json(); if (data.success) { currentUserId = data.userId; alert('注册成功!'); loadShares(); } else { alert(data.error); } } async function createShare() { if (!currentUserId) return alert('请先注册'); const targetUrl = document.getElementById('targetUrl').value.trim(); const platform = document.getElementById('platform').value; if (!targetUrl) return alert('请输入目标网址'); if (!targetUrl.startsWith('http')) return alert('网址必须以 http 或 https 开头'); const res = await fetch('/api/create-share', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ userId: currentUserId, targetUrl, platform }) }); const data = await res.json(); if (data.success) { document.getElementById('shareResult').innerHTML = ` <p>✅ 分享链接已生成:</p> <a href="${data.shareLink}" target="_blank">${data.shareLink}</a> `; loadShares(); } else { alert(data.error); } } async function loadShares() { if (!currentUserId) return; const res = await fetch(`/api/user-shares/${currentUserId}`); const shares = await res.json(); const list = document.getElementById('shareList'); list.innerHTML = shares.map(s => ` <div> <strong>平台:</strong>${s.platform} &nbsp; <strong>链接:</strong><a href="/s/${s.id}" target="_blank">/s/${s.id}</a> &nbsp; <strong>点击:</strong>${s.click_count} &nbsp; <strong>时间:</strong>${s.created_at} </div> `).join(''); } ``` --- ## 🚀 如何真实分享到抖音、QQ、百度 | 平台 | 模拟分享URL | 说明 | |------|-------------|------| | 百度 | `https://tieba.baidu.com/f?kw=share` | 跳转到百度贴吧指定吧,可改造 | | QQ | `https://connect.qq.com/widget/shareqq/index.html?url=你的链接` | QQ互联分享组件 | | 抖音 | `https://www.douyin.com/share/note/你的链接` | 抖音分享笔记URL | > **注意**:真实分享需要配合各平台的 **开放平台API**(如QQ互联、抖音开放平台)获取用户授权,本文使用了模拟跳转,便于演示。 --- ## 📌 开发建议 - **安全性**:密码应使用 bcrypt 加密存储,本示例为简化未实现。 - **短链接优化**:使用 Base62 编码生成更短的ID,避免UUID过长。 - **分布式部署**:如需高并发,将 SQLite 替换为 PostgreSQL 或 MySQL。 - **前端增强**:添加二维码生成(使用 qrcode.js)、一键复制等交互。 - **平台真实分享**:接入微信JS-SDK、微博开放接口等需注册应用并获取 appid。 --- ## ❓ 常见问题 1. **为什么分享后跳转到其他平台?** 我实现了平台定向跳转模拟,你可以根据需要修改成目标网站 URL 或真实分享接口。 2. **如何持久化用户登录状态?** 建议使用 JWT Token,前端存储到 localStorage,每次请求携带 Authorization header。 3. **如何统计多维数据?** 数据库已有 click_count,可扩展 `user_agent`、`ip`、`地域` 等字段做分析。 --- ######[AI写代码神器 | 2971点数解答 | 2026-06-11 10:11:27]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]