使用节点js创建HTTPS服务器

Him*_*dav 21 https node.js

我想为我的localhost创建一个https服务器.
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);
Run Code Online (Sandbox Code Playgroud)

要么

var options = {
  pfx: fs.readFileSync('server.pfx')
};
Run Code Online (Sandbox Code Playgroud)

在这里我如何获得我的localhost的密钥,证书或pfx?

Pas*_*itz 39

出于开发目的,您可以创建自我认证的证书.以下是如何在基于Linux的系统上执行此操作:

首先,生成私钥

openssl genrsa 1024 > key.pem
Run Code Online (Sandbox Code Playgroud)

这将在文件key.pem中存储1024位RSA密钥

然后,使用该密钥生成SSL证书:

openssl req -x509 -new -key key.pem > key-cert.pem
Run Code Online (Sandbox Code Playgroud)

现在,您可以在传递给createServer的选项中使用key.pem和key-cert.pem.