Skip to main content

在开发中使用 HTTPS

注意:react-scripts@0.4.0 及更高版本提供此功能。

¥Note: this feature is available with react-scripts@0.4.0 and higher.

你可能需要开发服务器通过 HTTPS 提供页面。这可能有用的一种特殊情况是,当 API 服务器本身提供 HTTPS 服务时,使用 "proxy" 功能 将请求代理到 API 服务器。

¥You may require the dev server to serve pages over HTTPS. One particular case where this could be useful is when using the "proxy" feature to proxy requests to an API server when that API server is itself serving HTTPS.

为此,将 HTTPS 环境变量设置为 true,然后像往常一样使用 npm start 启动开发服务器:

¥To do this, set the HTTPS environment variable to true, then start the dev server as usual with npm start:

Windows (cmd.exe)

set HTTPS=true&&npm start

(注意:缺少空格是有意的。)

¥(Note: the lack of whitespace is intentional.)

Windows (Powershell)

($env:HTTPS = "true") -and (npm start)

Linux、macOS(Bash)

HTTPS=true npm start

请注意,服务器将使用自签名证书,因此你的网络浏览器几乎肯定会在访问该页面时显示警告。

¥Note that the server will use a self-signed certificate, so your web browser will almost definitely display a warning upon accessing the page.

自定义 SSL 证书

¥Custom SSL certificate

要设置自定义证书,请按照与上述 HTTPS 相同的方式将 SSL_CRT_FILESSL_KEY_FILE 环境变量设置为证书和密钥文件的路径。请注意,你还需要设置 HTTPS=true

¥To set a custom certificate, set the SSL_CRT_FILE and SSL_KEY_FILE environment variables to the path of the certificate and key files in the same way you do for HTTPS above. Note that you will also need to set HTTPS=true.

Linux、macOS(Bash)

HTTPS=true SSL_CRT_FILE=cert.crt SSL_KEY_FILE=cert.key npm start

为避免每次都必须设置环境变量,你可以像这样在 npm start 脚本中包含:

¥To avoid having to set the environment variable each time, you can either include in the npm start script like so:

{
"start": "HTTPS=true react-scripts start"
}

或者你可以创建一个设置了 HTTPS=true.env 文件。详细了解 CRA 中的环境变量

¥Or you can create a .env file with HTTPS=true set. Learn more about environment variables in CRA.