给定 SSL 密钥和证书,如何创建 HTTPS 服务?
如何在 Node.js 中创建 HTTPS 服务器?
IT技术
javascript
node.js
ssl
https
webserver
2021-02-02 02:43:34
6个回答
该快递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);
对于 Node 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.pem
证书fullchain.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`)
};
在谷歌搜索“node https”时发现了这个问题,但接受的答案中的例子很旧 - 取自当前(v0.10)版本节点的文档,它应该是这样的:
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
上面的答案很好,但是使用 Express 和 node 这将正常工作。
由于 express 为您创建了应用程序,因此我将在此处跳过。
var express = require('express')
, fs = require('fs')
, routes = require('./routes');
var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();
// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});
Node.js 中 HTTPS 服务器的最小设置是这样的:
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/server-crt.pem')
};
var app = function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}
https.createServer(httpsOptions, app).listen(4433);
如果您还想支持 http 请求,则只需进行以下小修改:
var http = require('http');
var https = require('https');
var fs = require('fs');
var httpsOptions = {
key: fs.readFileSync('path/to/server-key.pem'),
cert: fs.readFileSync('path/to/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);