Node.js HTTPS not working



我正在尝试使用Node.js创建HTTPS服务器。我遵循了web上的一些说明,最终得到了以下代码:

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');

当尝试从Chrome访问时,我得到以下错误:

SSL连接错误无法与服务器建立安全连接。这可能是服务器的问题,也可能需要客户端您没有的身份验证证书。错误代码:ERR_SSL_procol_ERROR

有什么建议吗?

问题是您的SSL证书是自签名的,或者没有可用的SSL证书。

要绕过SSL证书的测试,您可以添加以下行:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';

如果您使用windows服务器

我建议以下步骤

步骤1:

为了从可信来源购买ssl,我使用了ssls.com

步骤2:

在iis 上安装ssl

步骤3:

将ssl证书导出到pfx文件,使用digiCertUtil.exe在此处下载

在此处输入图像描述

在此处输入图像描述

步骤4:

使用openssl 生成privakey.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

步骤5:

在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);

最新更新