如何使用 create-react-app 提供 SSL 证书?

新手上路,请多包涵

我正在尝试托管我使用 facebook 样板在本地创建和测试的反应应用程序。

客户端应用程序与我使用 node.js 制作的 API 交互,并且使用它设置安全连接没有问题(使用 node.js 客户端发送我的 SSL 证书,用于测试)。

但是,在使用 react 发送我的 SSL 证书而不是自签名证书时,我遇到了困难,这导致我在使用 chrome 并尝试访问 https://example.net:3000 时遇到此错误:

您的连接不是私有的 (NET:ERR_CERT_AUTHORITY_INVALID)

该文档对我的帮助不大:

请注意,服务器将使用自签名证书,因此您的网络浏览器几乎肯定会在访问页面时显示警告。 https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#using-https-in-development

如何使用我自己的 SSL 证书(我已经在我域上的另一个应用程序上使用它并且像一个魅力一样工作)而不是这个自签名证书?我错过了什么 ?

原文由 mjarraya 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

I was able to get a local certificate working without modifying the webpack-dev-server files using react-scripts 3.4.1 (technically added in 3.4.0 but I had some ——可能不相关的——问题)。我将这两个环境变量添加到我的 .env.development

 SSL_CRT_FILE=.cert/server.crt
SSL_KEY_FILE=.cert/server.key

笔记:

原文由 Andi 发布,翻译遵循 CC BY-SA 4.0 许可协议

更新:请参阅下面安迪的 回答。在最新版本中,您应该设置环境变量来配置证书

SSL_CRT_FILE=.cert/server.crt
SSL_KEY_FILE=.cert/server.key


弹出 create-react-app 不推荐,因为您将无法无缝升级它。此外,您无需弹出即可轻松获得有效的 SSL 证书。

您需要将证书复制到 node_modules/webpack-dev-server/ssl/server.pem 。缺点是需要手动复制文件。但是,实现无缝连接的一种方法是添加创建符号链接的 postinstall 脚本。这是我创建的 脚本

 #!/bin/bash
# With create-react-app, a self signed (therefore invalid) certificate is generated.
# 1. Create some folder in the root of your project
# 2. Copy your valid development certificate to this folder
# 3. Copy this file to the same folder
# 4. In you package.json, under `scripts`, add `postinstall` script that runs this file.
# Every time a user runs npm install this script will make sure to copy the certificate to the
# correct location

TARGET_LOCATION="./node_modules/webpack-dev-server/ssl/server.pem"
SOURCE_LOCATION=$(pwd)/$(dirname "./local-certificate/server.pem")/server.pem

echo Linking ${TARGET_LOCATION} TO ${SOURCE_LOCATION}
rm -f ${TARGET_LOCATION} || true
ln -s ${SOURCE_LOCATION} ${TARGET_LOCATION}
chmod 400 ${TARGET_LOCATION} # after 30 days create-react-app tries to generate a new certificate and overwrites the existing one.
echo "Created server.pem symlink"

您的 package.json 应该类似于:

 "scripts": {
    ...
    "postinstall": "sh ./scripts/link-certificate.sh"
}

  • 我的解决方案基于此 线程

原文由 Elad 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题