简体   繁体   English

Node.js HTTPS 不起作用

[英]Node.js HTTPS not working

I'm trying to create HTTPS server with Node.js.我正在尝试使用 Node.js 创建 HTTPS 服务器。 I have followed some instructions from web and end up with this code:我遵循了网络上的一些说明,最终得到了以下代码:

var https = require('https');
var fs = require('fs');

var options = {
  key: fs.readFileSync('D:\\NodeJs\\HTTPS\\keys\\pvtkey.pem', 'utf8'),
  cert: fs.readFileSync('D:\\NodeJs\\HTTPS\\keys\\cert.pem', 'utf8'),
  requestCert: false,
  rejectUnauthorized: false
};

https.createServer(options, function (req, res) {

  if (req.client.authorized) {
        res.writeHead(200, {"Content-Type": "application/json"});
        res.end('{"status":"approved"}');
    } else {
        res.writeHead(401, {"Content-Type": "application/json"});
        res.end('{"status":"denied"}');
    }

}).listen(443);

console.log('start listing');

When trying access from Chrome, I get the following error:尝试从 Chrome 访问时,出现以下错误:

SSL connection error Unable to make a secure connection to the server. SSL 连接错误 无法与服务器建立安全连接。 This may be a problem with the server, or it may be requiring a client authentication certificate that you don't have.这可能是服务器的问题,或者可能需要您没有的客户端身份验证证书。 Error code: ERR_SSL_PROTOCOL_ERROR错误代码:ERR_SSL_PROTOCOL_ERROR

Any advice?有什么建议吗?

The problem is that your SSL certificate is either self signed or there is no SSL certificate available.问题是您的 SSL 证书是自签名的,或者没有可用的 SSL 证书。

To bypass testing of SSL certificates you can add the following line:要绕过 SSL 证书的测试,您可以添加以下行:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

if you use windows server如果您使用 Windows 服务器

I suggest the following steps我建议以下步骤

step 1:第1步:

To buy ssl from a trusted source, I used ssls.com要从可信赖的来源购买 ssl,我使用了 ssls.com

step 2:第2步:

install ssl on iis在 iis 上安装 ssl

step 3:第 3 步:

export ssl certificate to pfx file, use digiCertUtil.exe download here将 ssl 证书导出到 pfx 文件,使用 digiCertUtil.exe在此处下载

enter image description here在此处输入图片说明

enter image description here在此处输入图片说明

step 4:第四步:

generate privkey.pem and fullchain.pem files use openssl使用 openssl 生成 privkey.pem 和 fullchain.pem 文件

openssl pkcs12 -in example.pfx -nocerts -nodes -out privkey.pem -passin pass:pfx-password -passout pass:new-password

openssl pkcs12 -in example.pfx -nokeys -out fullchain.pem -passin pass:pfx-password -passout pass:new-password

step 5:第 5 步:

use in node.js app在 node.js 应用程序中使用

 var express = require('express'); var https = require('https'); var http = require('http'); var fs = require('fs'); var options = { key: fs.readFileSync('privkey.pem'), cert: fs.readFileSync('fullchain.pem') }; var app = express(); app.get('/', (req, res) => { res.send('Hollo world') }) https.createServer(options, app).listen(8883);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM