2025-10-23 09:50:10 +08:00

64 lines
1.5 KiB
JavaScript

const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
require('dotenv').config();
const apiRoutes = require('./routes/api');
const app = express();
const PORT = process.env.PORT || 3001;
// 安全中间件
app.use(helmet());
app.set('trust proxy', true);
// 跨域配置
app.use(cors({
origin: process.env.FRONTEND_URL || 'https://feishuexcel.kinlim.com',
credentials: true
}));
// 请求限制
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15分钟
max: 100, // 限制每个IP 15分钟内最多100个请求
message: '请求过于频繁,请稍后再试'
});
app.use('/api/', limiter);
// 解析JSON请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true }));
// API路由
app.use('/api', apiRoutes);
// 健康检查端点
app.get('/health', (req, res) => {
res.json({ status: 'OK', timestamp: new Date().toISOString() });
});
// 错误处理中间件
app.use((err, req, res, next) => {
console.error('服务器错误:', err);
res.status(500).json({
success: false,
message: '服务器内部错误',
error: process.env.NODE_ENV === 'development' ? err.message : '服务器错误'
});
});
// 404处理
app.use('*', (req, res) => {
res.status(404).json({
success: false,
message: '接口不存在'
});
});
app.listen(PORT, () => {
console.log(`后端服务已启动,端口: ${PORT}`);
console.log(`健康检查: http://localhost:${PORT}/health`);
});
module.exports = app;