首页 > 解决方案 > 在 HTTPS 而不是 HTTP 中启动反应应用程序

问题描述

我想知道如何启动使用 https 而不是 HTTP 中的 create-react-app 命令制作的反应应用程序?

标签: reactjscreate-react-app

解决方案


使用类似 Root SSL 证书

生成密钥

openssl genrsa -des3 -out rootCA.key 2048

使用他们的密钥,您可以生成有效期为 1,024 天的证书

openssl req -x509 -new -nodes -key rootCA.key -sha256 -days 1024 -out rootCA.pem

在您的 Mac 上打开钥匙串访问并转到证书类别并导入从上一步生成的 rootCA.pem。双击并在“使用此证书时”下选择“始终信任”

创建 OpenSSL 配置文件

 server.csr.cnf

 [req]
 default_bits = 2048
 prompt = no
 default_md = sha256
 distinguished_name = dn

 [dn]
 C=US
 ST=RandomState
 L=RandomCity
 O=RandomOrganization
 OU=RandomOrganizationUnit
 emailAddress=hello@example.com
 CN = localhost

创建 v3.ext 文件以创建 X509 v3 证书。

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost

使用存储在 server.csr.cnf 中的配置设置为 localhost 创建证书密钥。此密钥存储在 server.key 中。

openssl req -new -sha256 -nodes -out server.csr -newkey rsa:2048 -keyout server.key -config <( cat server.csr.cnf )

证书签名请求是通过我们之前创建的根 SSL 证书发出的,用于为 localhost 创建域证书。输出是一个名为 server.crt 的证书文件。

openssl x509 -req -in server.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out server.crt -days 500 -sha256 -extfile v3.ext

您现在已准备好使用 HTTPS 保护您的本地主机。将 server.key 和 server.crt 文件移动到服务器上可访问的位置,并在启动服务器时包含它们。

在用 Node.js 编写的 Express 应用程序中,您可以这样做。确保仅针对本地环境执行此操作。不要在生产中使用它。

var path = require('path')
var fs = require('fs')
var express = require('express')
var https = require('https')

var certOptions = {
  key: fs.readFileSync(path.resolve('build/cert/server.key')),
  cert: fs.readFileSync(path.resolve('build/cert/server.crt'))
}

var app = express()

var server = https.createServer(certOptions, app).listen(443)

检查https://github.com/dakshshah96/local-cert-generator/ 以获得更详细的说明


推荐阅读