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


当前回答

你也可以在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命令。密钥输出服务器。如果需要编写测试,请使用证书来创建文件)

其他回答

你也可以在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命令。密钥输出服务器。如果需要编写测试,请使用证书来创建文件)

对于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`)
};

在谷歌搜索“节点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});

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);