This commit is contained in:
zhangyonghao
2026-03-21 17:16:13 +08:00
commit 6cf78d4c86
31 changed files with 970 additions and 0 deletions

View File

@@ -0,0 +1,70 @@
const express = require('express');
const cors = require('cors');
const dotenv = require('dotenv');
const fs = require('fs');
const path = require('path');
// 加载环境变量
dotenv.config();
const app = express();
const port = 8000;
// 中间件
app.use(cors());
app.use(express.json());
// 生成唯一 ID
function generateUniqueId() {
return Math.random().toString(36).substring(2, 18) + Math.random().toString(36).substring(2, 18);
}
// 确保静态文件目录存在
const staticDir = path.resolve(__dirname, '../frontend/public/static');
if (!fs.existsSync(staticDir)) {
fs.mkdirSync(staticDir, { recursive: true });
}
// API 路由
app.post('/api/html/generate', (req, res) => {
try {
const { html_content } = req.body;
if (!html_content) {
return res.status(400).json({ error: 'HTML 内容不能为空' });
}
// 生成唯一 ID
const uniqueId = generateUniqueId();
// 生成 HTML 文件路径
const htmlFilename = `${uniqueId}.html`;
const htmlPath = path.join(staticDir, htmlFilename);
// 写入 HTML 内容
fs.writeFileSync(htmlPath, html_content, 'utf-8');
// 生成完整链接
const frontendBaseUrl = process.env.FRONTEND_BASE_URL || 'http://localhost:3000';
const htmlUrl = `${frontendBaseUrl}/static/${htmlFilename}`;
res.status(201).json({
message: 'HTML 文件生成成功',
unique_id: uniqueId,
url: htmlUrl
});
} catch (error) {
console.error('生成 HTML 文件失败:', error);
res.status(500).json({ error: `生成 HTML 文件失败: ${error.message}` });
}
});
// 健康检查
app.get('/', (req, res) => {
res.json({ message: 'HTML Generator API is running' });
});
// 启动服务器
app.listen(port, () => {
console.log(`服务器运行在 http://localhost:${port}`);
});