如何在 Node.js 中使用 HTTPS

mar*_*are 3 ssl https openssl http node.js

我对 HTTPS、SSL 等几乎没有经验。

我想知道如何通过 HTTPS 使用 Node.js。我知道如何很好地使用 node.js,但是在使用 HTTPS 时它会出错。

我想我需要安装一些东西(openSSL?)。我想知道我必须在 Windows 8.1 计算机上安装的所有东西(不,我不想获得任何形式的 linux。也没有 cygwin),以便使用 node.js HTTPS 服务器。

我不需要有付费证书,我只需要让它工作。它没有接收来自浏览器的请求,所以我不关心付费证书。

Joh*_*ers 6

在您的系统上安装 node.js 后,只需按照以下步骤操作即可运行一个支持 HTTP 和 HTTPS 的基本 Web 服务器!

第 1 步:建立证书颁发机构

  1. 创建要存储密钥和证书的文件夹:

    mkdir conf


  1. 转到该目录:

    cd conf


  1. 获取此ca.cnf文件以用作配置快捷方式:

    wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/ca.cnf


  1. 使用此配置创建一个新的证书颁发机构:

    openssl req -new -x509 -days 9999 -config ca.cnf -keyout ca-key.pem -out ca-cert.pem


  1. 现在我们在ca-key.pemand 中拥有我们的证书颁发机构ca-cert.pem,让我们为服务器生成一个私钥:

    openssl genrsa -out key.pem 4096


  1. 获取此server.cnf文件以用作配置快捷方式:

    wget https://raw.githubusercontent.com/anders94/https-authorized-clients/master/keys/server.cnf


  1. 使用此配置生成证书签名请求:

    openssl req -new -config server.cnf -key key.pem -out csr.pem


  1. 签署请求:

    openssl x509 -req -extfile server.cnf -days 999 -passin "pass:password" -in csr.pem -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out cert.pem


第 2 步:将您的证书安装为根证书

  1. 将您的证书复制到根证书的文件夹中:

    sudo cp ca-crt.pem /usr/local/share/ca-certificates/ca-crt.pem


  1. 更新 CA 存储:

    sudo update-ca-certificates


第 3 步:启动您的节点服务器

首先,确保你的代码server.js看起来像这样:

var http = require('http');
var https = require('https');
var fs = require('fs');

var httpsOptions = {
    key: fs.readFileSync('/path/to/HTTPS/server-key.pem'),
    cert: fs.readFileSync('/path/to/HTTPS/server-crt.pem')
};

var app = function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}

http.createServer(app).listen(8888);
https.createServer(httpsOptions, app).listen(4433);
Run Code Online (Sandbox Code Playgroud)
  1. 转到您所在的目录server.js

    cd /path/to


  1. 运行server.js

    node server.js