如何在Node.js中创建HTTPS服务器?

2022-08-29 23:28:27

给定 SSL 密钥和证书,如何创建 HTTPS 服务?


答案 1

Express API文档非常清楚地说明了这一点。

此外,此答案还提供了创建自签名证书的步骤。

我从Node.js HTTPS文档中添加了一些注释和一个片段:

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

// This line is from the Node.js HTTPS documentation.
var options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.cert')
};

// Create a service (the app object is just a callback).
var app = express();

// Create an HTTP service.
http.createServer(app).listen(80);
// Create an HTTPS service identical to the HTTP service.
https.createServer(options, app).listen(443);

答案 2

对于节点 0.3.4 及更高版本,一直到当前的 LTS(本次编辑时为 v16),https://nodejs.org/api/https.html#httpscreateserveroptions-requestlistener 具有您需要的所有示例代码:

const https = require(`https`);
const fs = require(`fs`);

const options = {
  key: fs.readFileSync(`test/fixtures/keys/agent2-key.pem`),
  cert: fs.readFileSync(`test/fixtures/keys/agent2-cert.pem`)
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end(`hello world\n`);
}).listen(8000);

请注意,如果要通过 certbot 工具使用 Let's Encrypt 的证书,则会调用私钥,并调用证书:privkey.pemfullchain.pem

const certDir = `/etc/letsencrypt/live`;
const domain = `YourDomainName`;
const options = {
  key: fs.readFileSync(`${certDir}/${domain}/privkey.pem`),
  cert: fs.readFileSync(`${certDir}/${domain}/fullchain.pem`)
};