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



我正在尝试创建一个HTTPS服务器。我已经生成了私钥。Pem和证书。使用Cygwin64执行以下操作:

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 worldn");
}).listen(8001);

当我尝试连接地址https://localhost:8001时,网页不可用。有人能帮我吗?

您的代码绝对运行良好。我已经在我的本地主机上测试了它。我认为问题出在你们关键的一代。尝试再次生成密钥并运行服务器。我希望它能起作用。

注意:您正在生成的证书将仅在本地主机上工作。因此,不要在任何在线IDE(如codio.com, koding.com, cloud9.com等)中尝试此操作。如果你想这样做,你必须从Verysign这样的公司购买SSL证书。

<标题>或

如果没有,试试下面的代码。

步骤1:打开终端,运行以下命令生成私钥文件'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 worldn");
}).listen(8001);

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

$ node server.js

步骤5:现在在浏览器中点击url 'https://localhost:8001'并接受证书,您将在页面上看到'hello world'消息

最新更新