You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在非标准端口上配置Node.js服务支持HTTPS访问

问题根源

你遇到的SSL_ERROR_RX_RECORD_TOO_LONG报错核心原因是HTTPS协议请求发送到了HTTP服务端口:你3000端口默认跑的是HTTP明文服务,客户端发起SSL握手请求时,服务端返回的是HTTP明文响应,SSL解析时无法识别就抛出了长度超限错误。
你直接把http.createServer替换为https.createServer不生效,是因为HTTPS服务启动必须加载SSL证书和私钥,你没有传入对应的证书参数,HTTPS服务没有正常启动。

推荐解决方案

优先选第一种方案,适配共享主机的限制:

方案1:用现有Web服务做反向代理(推荐)

你的主机已经配置好Let's Encrypt证书,https://example.net可以正常访问,说明主机已经部署了Nginx/Apache等Web服务,直接通过反向代理把Node服务挂载到现有HTTPS站点下即可,无需修改Node代码、无需额外开放端口:

  • 找到你站点的HTTPS配置文件(以Nginx为例),在server块中添加如下配置:
# 如果你想通过 https://example.net/ 直接访问Node服务
location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}
# 如果你想保留原有站点内容,单独通过子路径访问Node服务,就改成location /node-service/ 即可
  • 重载Nginx配置后,直接访问https://example.net就可以正常访问Node服务,证书复用现有配置,自动续期也不需要额外处理。

方案2:Node服务直接启动HTTPS

如果需要单独用端口提供HTTPS服务,可以修改Node代码,加载你主机上的Let's Encrypt证书:

const app = require("express")();
const https = require("https");
const fs = require("fs");
const port = process.env.PORT || 3000;

// 替换为你主机上Let's Encrypt证书的实际路径
const options = {
  cert: fs.readFileSync("/etc/letsencrypt/live/example.net/fullchain.pem"),
  key: fs.readFileSync("/etc/letsencrypt/live/example.net/privkey.pem")
};

const httpsServer = https.createServer(options, app);

app.get('/', function (req, res, next) {
  res.sendFile(__dirname + '/index.html');
});

httpsServer.listen(port, () => {
  console.log("HTTPS服务运行在端口" + port);
});

修改后需要确认:

  • 共享主机的防火墙开放了3000端口的HTTPS入站规则
  • 每次Let's Encrypt证书自动续期后,要重启Node服务加载新证书

内容的提问来源于stack exchange,提问作者Cain Nuke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 03:36:03