有了SSL密钥和证书,如何创建HTTPS服务?
有了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);
https.createServer
中首先放置 options
,以避免出现晦涩的错误。 - wberryopenssl genrsa -out key.pem 2048
。 - sakisk从 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);
请注意,如果想要使用Let's Encrypt的证书并使用Certbot工具,私钥应该被称为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`)
};
setSecure
已被弃用。请查看替代方案:https://dev59.com/vW435IYBdhLWcg3w6EqF - Larry Battle在Google搜索“node https”时发现了这个问题,但被采纳的答案中的示例非常古老 - 取自当前(v0.10)版本的Node.js文档,它应该像这样:
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);
openssl
,然后在命令提示符中键入openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 3001
。 - midohttps://localhost:8080
。HTTP 不是 HTTPS。 - Florian Wendelborn上面的回答都不错,但使用 Express 和 node.js 也可以很好地实现。
由于 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});
module.exports
?这并不必要。 - Matejvar 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);
createServer
已经被弃用了!这个函数不再存在。 - ThNcreateServer
已经不存在了吗?它仍然在 Node.js v16.5.0 的文档中有记录,而且在 https://nodejs.org/api/http.html 和 https://nodejs.org/api/https.html 中都没有被标记为弃用。你真的尝试运行过这段代码吗?如果是的话,你遇到了哪些错误? - John Slegersvar https = require('https').Server(app);
为 var https = require('https');
现在,一切都正常了...谢谢。 - ThN使用Greenlock.js通过Let's Encrypt进行
我注意到这些答案都没有显示如何添加中间根证书颁发机构到链中,以下是一些零配置示例,可供尝试查看:
片段:
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);
});
https
模块处理它,然后使用它来为您提供连接/表达式应用程序。此外,如果您在创建服务器时使用server.on('request', app)
而不是传递应用程序,则可以将server
实例传递给某些初始化函数,该函数创建连接/表达式应用程序(例如,如果您想在同一服务器上进行基于ssl的websockets)。var https = require("https").server(app);
当我使用 https.createServer(...)
创建服务器时,我收到了错误消息 createServer 未找到。将该行更改为 var https = require("https");
后,一切都顺利了。谢谢... - ThN80
和443
上的http
和https
,请执行以下操作:var express = require('express');
var app = express();
< p>由< code>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);
完整详情请参见文档
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
创建文件。
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();
它: