node.js上的服务器HTTPS不起作用 [英] Server HTTPS on node.js doesn't work

查看:220
本文介绍了node.js上的服务器HTTPS不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建HTTPS服务器。我按照以下说明生成了带有Cygwin64的privatekey.pem和certicate.pem:

I'm trying to create an HTTPS server. I have generated privatekey.pem and certicate.pem with Cygwin64 following these instructions:

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

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

while my server code is this:

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 ,该网页不可用。任何人都可以帮助我吗?

When i try to connect to address https://localhost:8001, the web page is not available. Can anyone help me?

推荐答案

你的代码绝对正常。我在我的localhost中测试过它。我认为问题在于您的密钥生成。尝试再次生成密钥并运行您的服务器。我希望它能运作。

Your code is absolutely working fine. I have tested it in my localhost. I think the issue is with your key generation. Try to generate once again the keys and run your server. I hope it will work.

注意:您生成的证书只能在localhost中使用。所以不要在任何在线IDE(如codio.com,koding.com,cloud9.com等)中尝试这一点。如果你想这样做,你必须从Verysign公司购买SSL证书。

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

If not try the below code.

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

Step 1: Open your terminal and run the following command to generate private key file 'key.pem'.

$ openssl genrsa 1024 > key.pem

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

Step 2: Now run the following command to generate SSL Certificate file 'key-cert.pem'.

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

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

Step 3: Now write the 'server.js' file with the following content.

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:现在使用以下命令运行服务器文件。

Step 4: Now run the server file using following command.

$ node server.js

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

Step 5: Now in the browser hit the url 'https://localhost:8001' and accept the certificate and you will see the 'hello world' message on the page.

这篇关于node.js上的服务器HTTPS不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆