一尘不染

如何在Node.js中创建HTTPS服务器?

node.js

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


阅读 233

收藏
2020-07-07

共1个答案

一尘不染

我发现以下示例。

https://web.archive.org/web/20120203022122/http://www.silassewell.com/blog/2010/06/03/node-
js-https-ssl-server-
example/

这适用于节点v0.1.94-v0.3.1。server.setSecure()在新版本的节点中被删除。

直接从该来源:

const crypto = require('crypto'),
  fs = require("fs"),
  http = require("http");

var privateKey = fs.readFileSync('privatekey.pem').toString();
var certificate = fs.readFileSync('certificate.pem').toString();

var credentials = crypto.createCredentials({key: privateKey, cert: certificate});

var handler = function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World\n');
};

var server = http.createServer();
server.setSecure(credentials);
server.addListener("request", handler);
server.listen(8000);
2020-07-07