// 简单的请求频率限制中间件 const rateLimit = {}; const rateLimitMiddleware = (req, res, next) => { const ip = req.ip || req.connection.remoteAddress; const now = Date.now(); const windowMs = 60000; // 1分钟 const maxRequests = 100; // 每分钟最多100次 if (!rateLimit[ip]) { rateLimit[ip] = { count: 1, resetTime: now + windowMs }; return next(); } // 检查是否在时间窗口内 if (now > rateLimit[ip].resetTime) { rateLimit[ip] = { count: 1, resetTime: now + windowMs }; return next(); } // 检查请求次数 if (rateLimit[ip].count >= maxRequests) { return res.status(429).json({ error: 'Too many requests', retryAfter: Math.ceil((rateLimit[ip].resetTime - now) / 1000) }); } rateLimit[ip].count++; next(); }; // 清理过期的记录(每5分钟) setInterval(() => { const now = Date.now(); for (const ip in rateLimit) { if (now > rateLimit[ip].resetTime) { delete rateLimit[ip]; } } }, 300000); module.exports = rateLimitMiddleware;