Node.js HTTPS服务器出现404错误,请求协助排查修复
问题修复方案
核心问题分析
出现404错误且请求计数为0,根源在于两个关键问题:
- 访问URL格式错误:HTTPS默认端口是443,非默认端口的正确写法是
https://域名:端口/路径。你使用的https://thebomberman.net/game:3000会被服务器解析为请求路径/game:3000,而你的代码只匹配根路径/,因此返回404。 - 路由未覆盖目标路径:即便URL格式正确,当前代码也没有处理
/game路径的逻辑,同样会触发404。
具体修复步骤
1. 修正访问URL
将访问地址改为正确格式:
https://thebomberman.net:3000/game
本地测试则用:
https://localhost:3000/game
2. 更新代码路由逻辑
修改请求处理部分,添加/game路径的匹配,同时移除重复的请求监听(避免计数错误):
const https = require('https'); const fs = require('fs'); const options = { key: fs.readFileSync('server.key'), cert: fs.readFileSync('server.cert') }; let requestCount = 0; const server = https.createServer(options, (req, res) => { requestCount++; console.log("req.url:", req.url); // 匹配根路径和/game路径 if (req.url === '/' || req.url === '/game') { res.end('Hello, world!'); } else { res.statusCode = 404; res.setHeader('Content-Type', 'text/plain'); res.end('Custom 404: The requested resource was not found.'); } }); server.listen(3000, () => { console.log('Server is running on port 3000'); }); server.on('clientError', (error, socket) => { console.error('Client error:', error); socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); }); server.on('error', (error) => { console.error('Server error:', error); }); process.on('SIGINT', () => { console.log('Received SIGINT. Shutting down...'); server.close(() => { console.log('Server has stopped'); process.exit(0); }); }); setInterval(() => { console.log(`Total requests: ${requestCount}`); }, 5000);
3. 额外验证点
- 确认
server.key和server.cert文件存在于代码执行目录(你已确认端口监听正常,此步骤大概率没问题)。 - 远程服务器需检查防火墙是否开放3000端口,允许HTTPS流量通过。
内容的提问来源于stack exchange,提问作者Bhanu
相关产品推荐
相关产品推荐

