Node.js上的服务器HTTPS不起作用

我正在尝试创build一个HTTPS服务器。 我已经按照以下说明使用Cygwin64生成了privatekey.pem和certicate.pem:

openssl genrsa -out privatekey.pem 1024 openssl req -new -key privatekey.pem -out certrequest.csr openssl x509 -req -in certrequest.csr -signkey privatekey.pem -out certificate.pem 

而我的服务器代码是这样的:

 var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('privatekey.pem'), cert: fs.readFileSync('certificate.pem') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8001); 

当我尝试连接到地址https://localhost:8001 ,网页不可用。 谁能帮我?

你的代码绝对正常工作。 我已经在我的本地主机上进行了testing。 我认为问题在于你的关键一代。 尝试再次生成密钥并运行您的服务器。 我希望这会起作用。

注意:您正在生成的证书只能在本地主机上使用。 所以不要在任何在线的IDE(比如codio.com,koding.com,cloud9.com等)试试这个。 如果你想要做,你必须从像Verysign这样的公司购买SSL证书。

要么

如果不尝试下面的代码。

步骤1:打开您的terminal并运行以下命令生成私钥文件'key.pem'

 $ openssl genrsa 1024 > key.pem 

步骤2:现在运行以下命令生成SSL证书文件“key-cert.pem”

 $ openssl req -x509 -new -key key.pem > key-cert.pem 

第3步:现在写下'server.js'文件以下内容。

 var https = require('https'); var fs = require('fs'); var options = { key: fs.readFileSync('key.pem'), cert: fs.readFileSync('key-cert.pem') }; https.createServer(options, function (req, res) { res.writeHead(200); res.end("hello world\n"); }).listen(8001); 

第4步:现在使用以下命令运行服务器文件。

 $ node server.js 

第5步:现在在浏览器中点击'https://localhost:8001' ,接受证书,并在页面上看到“hello world”消息。