首页 > 解决方案 > 创建用于 Node.js 的 SSL 证书

问题描述

我需要在https协议上运行本地 Express 服务器。我使用了网站和类似网站的说明。但是当我试图在浏览器中打开页面时,我得到了Your connection is not private错误。当我从 中打开Security选项卡时Developer tools,我看到了This site is missing a valid, trusted certificate (net::ERR_CERT_INVALID)错误。当我尝试通过 Postman 发送请求时,我的服务器没有响应,并且curl请求返回:

curl: (60) SSL certificate problem: unable to get local issuer certificate

这是服务器代码:

const app = require('express')();
const fs = require('fs');
const https = require('https');

const options = {
  key: fs.readFileSync('./key.pem'),
  cert: fs.readFileSync('./cert.pem')
};

app.get('/', (req, res) => {
  res.send('hello world');
});

https
  .createServer(options, app)
  .listen(3000, '127.0.0.1', () => {
    console.log('Run on: https://127.0.0.1:3000');
  });

我使用下一个命令创建了证书:

$ openssl req -nodes -sha256 -new -x509 -keyout key.pem -out cert.pem -days 365 -config req.cnf

其中req.cnf文件具有以下内容:

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
C = US
ST = VA
L = SomeCity
O = MyCompany
OU = MyDivision
CN = 127.0.0.1:3000
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = IP:127.0.0.1:3000

我也尝试使用443端口,但不幸的是,我遇到了同样的错误。此外,我尝试https://127.0.0.1:3000使用隐身模式打开页面 - 没有发生任何事情 - 错误是相同的。

我的问题是:

  1. 创建证书我哪里错了?
  2. 为什么我不能通过 Postman/curl 向我的服务器发送请求?

标签: node.jssslhttps

解决方案


您创建的是自签名证书,默认情况下,没有网络应用程序会接受它们,因为它们无法验证它们,因此它们假设更糟(MITM 攻击)。

如果您只需要这个进行本地检查,那么您可以按照这个 Getting Chrome to accept self-signed localhost certificate

Postman 错误可能是 chrome 应用程序的等效错误。


推荐阅读