[英]How to create an HTTPS server in Node.js?
给定 SSL 密钥和证书,如何创建 HTTPS 服务?
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);
对于 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);
通过Greenlock.js使用 Let's Encrypt
我注意到这些答案都没有表明将中间根 CA添加到链中,这里有一些零配置示例可以查看:
片段:
var options = {
// this is the private key only
key: fs.readFileSync(path.join('certs', 'my-server.key.pem'))
// this must be the fullchain (cert + intermediates)
, cert: fs.readFileSync(path.join('certs', 'my-server.crt.pem'))
// this stuff is generally only for peer certificates
//, ca: [ fs.readFileSync(path.join('certs', 'my-root-ca.crt.pem'))]
//, requestCert: false
};
var server = https.createServer(options);
var app = require('./my-express-or-connect-app').create(server);
server.on('request', app);
server.listen(443, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
var insecureServer = http.createServer();
server.listen(80, function () {
console.log("Listening on " + server.address().address + ":" + server.address().port);
});
如果您不尝试直接通过 connect 或 express 执行此操作,那么这是通常更容易的事情之一,而是让本机https
模块处理它,然后使用它来为您连接/express 应用程序提供服务。
此外,如果您在创建服务器时使用server.on('request', app)
而不是传递应用程序,它使您有机会将server
实例传递给一些创建连接/快速应用程序的初始化函数(如果需要)例如,在同一台服务器上通过 ssl 执行websockets )。
要让您的应用分别在端口80
和443
上侦听http
和https
,请执行以下操作
创建一个快递应用:
var express = require('express');
var app = express();
express()
返回的应用程序是一个 JavaScript 函数。 它可以作为回调传递给 Node 的 HTTP 服务器来处理请求。 这使得使用相同的代码库轻松提供应用程序的 HTTP 和 HTTPS 版本。
你可以这样做:
var express = require('express');
var https = require('https');
var http = require('http');
var fs = require('fs');
var app = express();
var options = {
key: fs.readFileSync('/path/to/key.pem'),
cert: fs.readFileSync('/path/to/cert.pem')
};
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
有关完整的详细信息,请参阅文档
你也可以使用 Fastify 框架来存档:
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
key: readFileSync('./test/asset/server.key'),
cert: readFileSync('./test/asset/server.cert')
},
logger: { level: 'debug' }
})
fastify.listen(8080)
(如果需要编写测试,请运行openssl req -nodes -new -x509 -keyout server.key -out server.cert
来创建文件)
如果您只需要在本地进行本地开发,我已经为此任务创建了实用程序 - https://github.com/pie6k/easy-https
import { createHttpsDevServer } from 'easy-https';
async function start() {
const server = await createHttpsDevServer(
async (req, res) => {
res.statusCode = 200;
res.write('ok');
res.end();
},
{
domain: 'my-app.dev',
port: 3000,
subdomains: ['test'], // will add support for test.my-app.dev
openBrowser: true,
},
);
}
start();
它:
var path = require('path');
var express = require('express');
var app = express();
var staticPath = path.join(__dirname, '/public');
app.use(express.static(staticPath));
app.listen(8070, function() {
console.log('Server started at port 8070');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.