创建react应用程序
If you built an application using create-react-app
and you’re running it locally on your computer, by default it is served using the HTTP protocol.
如果您使用create-react-app
构建了应用create-react-app
并且在计算机上本地运行该create-react-app
,则默认情况下将使用HTTP协议为其提供服务。
Any application running in production will be served using HTTPS, the secure version of HTTP.
生产中运行的所有应用程序都将使用HTTPS(HTTP的安全版本)进行服务。
You will get HTTPS almost with no effort in most cases, especially if you use a modern platform like Netlify or Vercel to serve your app.
在大多数情况下,几乎可以毫不费力地获得HTTPS,尤其是如果您使用Netlify或Vercel之类的现代平台来服务您的应用程序时。
But locally.. it’s a bit more complicated that we’d like.
但是在本地..我们要复杂一点。
Let’s see how you can do it!
让我们看看如何做到!
As you know, the create-react-app
application is ran using npm run start
, or simply npm start
, because in the package.json
file’s scripts
section, we have this line:
如您所知, create-react-app
应用程序是使用npm run start
或简单地npm start
来npm start
,因为在package.json
文件的scripts
部分中,我们有以下一行:
"start": "react-scripts start"
change that to:
更改为:
"start": "HTTPS=true react-scripts start"
This sets the HTTPS
environment variable to the true
value.
这会将HTTPS
环境变量设置为true
值。
That’s not enough, though.
但是,这还不够。
Now we also need to generate a local certificate. This step will work fine for any app, not just create-react-app
apps, but I will include it in this post, as a reference.
现在,我们还需要生成本地证书。 此步骤适用于所有应用程序,不仅适用于create-react-app
应用程序,而且我还将在本博文中将其作为参考。
Note: I ran these commands on macOS. Linux should work in the same way. I don’t guarantee for Windows.
注意:我在macOS上运行了这些命令。 Linux应该以相同的方式工作。 我不保证使用Windows。
In the project root folder, run:
在项目根文件夹中,运行:
openssl req -x509 -newkey rsa:2048 -keyout keytmp.pem -out cert.pem -days 365
Now run:
现在运行:
openssl rsa -in keytmp.pem -out key.pem
You should now have the files cert.pem
and key.pem
in the folder.
现在,您应该在文件夹中包含文件cert.pem
和key.pem
。
Now change the start
script in the package.json
file to:
现在,将package.json
文件中的start
脚本更改为:
"start": "export HTTPS=true&&SSL_CRT_FILE=cert.pem&&SSL_KEY_FILE=key.pem react-scripts start",
If you ran npm run start
, and access https://localhost:3000
(or the port your app uses, if different - in my case it’s 3008), you should see this warning message:
如果您运行npm run start
并访问https://localhost:3000
(或应用程序使用的端口,如果不同,在我的情况下为3008),则应该看到以下警告消息:
To fix it on macOS, follow the instructions of my tutorial how to install a local certificate in macOS.
要在macOS上修复它,请按照我的教程如何在macOS中安装本地证书的说明进行操作 。
Once you do, you will be able to see the app without problems, served using SSL:
完成后,您将能够看到使用SSL投放的应用程序,而不会出现问题:
翻译自: https://flaviocopes.com/react-how-to-configure-https-localhost/
创建react应用程序