From 1bfbf5a31c390399d8895ac5318ba6b1974828b1 Mon Sep 17 00:00:00 2001 From: 1e0n Date: Tue, 7 Oct 2025 01:53:27 +0800 Subject: [PATCH] Add detailed 404 error logging for invalid requests - Log invalid request method, URL, path, and parameters - Display query parameters and request body if present - Show client IP and User-Agent information - Return helpful error message with available endpoints - Format console output with clear visual separators --- server.js | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/server.js b/server.js index d0ca0d0..6f0eee0 100644 --- a/server.js +++ b/server.js @@ -34,6 +34,64 @@ app.get('/', (req, res) => { }); }); +// 404 处理 - 捕获所有未匹配的路由 +app.use((req, res, next) => { + const errorInfo = { + timestamp: new Date().toISOString(), + method: req.method, + url: req.originalUrl || req.url, + path: req.path, + query: req.query, + params: req.params, + body: req.body, + headers: { + 'content-type': req.headers['content-type'], + 'user-agent': req.headers['user-agent'], + 'origin': req.headers['origin'], + 'referer': req.headers['referer'] + }, + ip: req.ip || req.connection.remoteAddress + }; + + console.error('\n' + '='.repeat(80)); + console.error('❌ 非法请求地址'); + console.error('='.repeat(80)); + console.error(`时间: ${errorInfo.timestamp}`); + console.error(`方法: ${errorInfo.method}`); + console.error(`地址: ${errorInfo.url}`); + console.error(`路径: ${errorInfo.path}`); + + if (Object.keys(errorInfo.query).length > 0) { + console.error(`查询参数: ${JSON.stringify(errorInfo.query, null, 2)}`); + } + + if (errorInfo.body && Object.keys(errorInfo.body).length > 0) { + console.error(`请求体: ${JSON.stringify(errorInfo.body, null, 2)}`); + } + + console.error(`客户端IP: ${errorInfo.ip}`); + console.error(`User-Agent: ${errorInfo.headers['user-agent'] || 'N/A'}`); + + if (errorInfo.headers.referer) { + console.error(`来源: ${errorInfo.headers.referer}`); + } + + console.error('='.repeat(80) + '\n'); + + logError('Invalid request path', errorInfo); + + res.status(404).json({ + error: 'Not Found', + message: `路径 ${req.method} ${req.path} 不存在`, + timestamp: errorInfo.timestamp, + availableEndpoints: [ + 'GET /v1/models', + 'POST /v1/chat/completions' + ] + }); +}); + +// 错误处理中间件 app.use((err, req, res, next) => { logError('Unhandled error', err); res.status(500).json({