如何使用 HTTPS 库在 Node.js 中托管具有有效证书的 HTTPS 服务器

How to host a HTTPS server with a valid certificate in Node.js using HTTPS library

我想托管自己的 https 服务器,但是我生成的证书无效,从浏览器访问时显示连接不安全。

您可以在您的 NodeJS 代码库中实现它,或者使用 NginxApache

来实现 http proxy
const crypto = require('crypto'),
  fs = require("fs"),
  http = require("http");

var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();

var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

var handler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
};

var server = http.createServer();
server.setSecure(credentials);
server.addListener("request", handler);
server.listen(8000);

推荐使用Nginx方式

https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04

在虚拟主机中添加 SSL 文件

如果您想使用免费的 SSL,试试 certbot,它会在 vhost 中自动安装 SSL

https://certbot.eff.org/