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

Node.js服务器HTTPS连接异常:Chrome提示不支持协议

问题:HTTPS服务器启动正常,但Chrome提示“无法提供安全连接,localhost使用不支持的协议”

服务器控制台显示已成功启动且无报错,但Chrome浏览器提示:

无法提供安全连接,localhost使用不支持的协议(原英文提示:This site can’t provide a secure connection local host uses an unsupported protocol)

以下是我的代码:

import express from 'express';
import https from 'https';
import fs from 'fs';
const app = express();

const PORT = process.env.Port || 443;
// app.listen(PORT,()=>{
//     console.log(`Server connected in Port ${PORT}`);
// })

const privateKey = fs.readFileSync('./private_key.key', (data, err) => {
  if (err) {
    return err;
  } else {
    return data;
  }
})


let certification = fs.readFileSync('./CA_certificate.arm', (data, err) => {
    if (err) {
      return err;
    } else {
      return data;
    }
  }),
  options = {
    key: privateKey,
    certificate: certification,
    passphrase: 'message',
    // secureProtocol: 'TLSv1.2'

  }
https.createServer(options, (req, res) => {
  res.statusCode(200);
  console.log("KHUSHI");
}).listen(PORT, () => {
  console.log(`Server started in Port` + PORT);
});

问题原因及修复方案

1. 同步文件读取方法误用回调

fs.readFileSync是同步读取方法,不需要传入回调函数。当前写法会让privateKey和certification拿到文件句柄而非实际的密钥/证书内容,导致HTTPS服务器无法正确加载证书,协议协商失败。

修复:移除回调,直接读取文件内容:

const privateKey = fs.readFileSync('./private_key.key', 'utf8');
const certification = fs.readFileSync('./CA_certificate.arm', 'utf8');

2. 证书格式或读取编码问题

你的证书后缀是.arm,标准HTTPS证书应为PEM格式(Base64编码的文本)。如果.arm是二进制格式,必须指定utf8编码才能正确读取文本内容;若证书本身格式错误,建议重新生成PEM格式的SSL证书。

3. 响应状态码设置错误

代码中res.statusCode(200)是错误写法,statusCode是响应对象的属性,需用赋值方式设置:

res.statusCode = 200;
// 或者用Express的便捷方法:
res.status(200).send('服务器正常运行');

4. 启用兼容的TLS协议

Chrome已废弃TLSv1.0、TLSv1.1等旧版本协议,需确保服务器启用TLSv1.2或更高版本。取消注释并修正secureProtocol配置:

const options = {
  key: privateKey,
  certificate: certification,
  passphrase: 'message',
  secureProtocol: 'TLSv1_2_method' // 注意此处为下划线,不是点
};

5. 本地证书信任配置

即使修复以上问题,Chrome仍可能提示证书不受信任。需将你的CA证书导入浏览器信任列表:

  • 打开Chrome设置 → 隐私和安全 → 安全 → 管理证书
  • 导入证书并设置为“信任该证书颁发机构”

修复后的完整代码

import express from 'express';
import https from 'https';
import fs from 'fs';
const app = express();

const PORT = process.env.Port || 443;

// 正确读取密钥和证书
const privateKey = fs.readFileSync('./private_key.key', 'utf8');
const certification = fs.readFileSync('./CA_certificate.arm', 'utf8');

const options = {
  key: privateKey,
  certificate: certification,
  passphrase: 'message',
  secureProtocol: 'TLSv1_2_method'
};

https.createServer(options, (req, res) => {
  res.statusCode = 200;
  res.end('HTTPS服务器运行正常');
}).listen(PORT, () => {
  console.log(`Server started on Port ${PORT}`);
});

内容的提问来源于stack exchange,提问作者Khushi Sanghvi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 14:30:42