如何使用create-react-app在本地设置HTTPS

Running HTTPS in development is helpful when you need to consume an API that is also serving requests via HTTPS.

当您需要使用同时通过HTTPS服务请求的API时,在开发中运行HTTPS会很有帮助。

In this article, we will be setting up HTTPS in development for our create-react-app with our own SSL certificate.

在本文中,我们将使用自己的SSL证书在我们的create-react-app开发中设置HTTPS。

This guide is for macOS users and requires that you have brew installed.

本指南适用于macOS用户,要求您已安装brew

添加HTTPS (Adding HTTPS)

In your package.json, update the start script to include https:

package.json ,将启动脚本更新为包含https:

"scripts": {
    "start": "HTTPS=true react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

Running yarn start after this step will show you this screen in your browser:

在此步骤之后yarn start运行yarn start将会在浏览器中显示以下屏幕:

At this stage, you're already set to go with https. But you don't have a valid certificate, so your connection is assumed to be insecure.

在此阶段,您已经设置为使用https 。 但是您没有有效的证书,因此假定您的连接不安全。

创建一个SSL证书 (Creating a SSL Certificate)

The easiest way to obtain a certificate is via mkcert.

获得证书的最简单方法是通过mkcert

# Install mkcert tool
brew install mkcert

# Install nss (only needed if you use Firefox)
brew install nss

# Setup mkcert on your machine (creates a CA)
mkcert -install

After running the above commands, you'll have created a certificate authority on your machine which enables you to generate certificates for all of your future projects.

运行上述命令后,您将在计算机上创建一个证书颁发机构 ,使您可以为以后的所有项目生成证书。

From the root of your create-react-app project, you should now run:

现在,应从create-react-app项目的根目录运行:

# Create .cert directory if it doesn't exist
mkdir -p .cert

# Generate the certificate (ran from the root of this project)
mkcert -key-file ./.cert/key.pem -cert-file ./.cert/cert.pem "localhost"

We'll be storing our generated certificates in the .cert directory. These should not be committed to version control, so you should update your .gitignore to include the .cert directory.

我们将生成的证书存储在.cert目录中。 这些不应提交给版本控制,因此您应更新.gitignore以包括.cert目录。

Next, we need to update the start script again to include our newly created certificate:

接下来,我们需要再次更新start脚本以包括我们新创建的证书:

"scripts": {
    "start": "HTTPS=true SSL_CRT_FILE=./.cert/cert.pem SSL_KEY_FILE=./.cert/key.pem react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

When you run yarn start again, you should now see that your connection is secure.

再次运行yarn start时,现在应该看到连接是安全的。

Don't be a stranger! Feel free to write if you have any questions - connect with me on Linkedin or follow me on Twitter.

不要成为陌生人! 如有任何疑问,请随时写信- 在Linkedin上与我联系,或在Twitter上关注我 。

翻译自: https://www.freecodecamp.org/news/how-to-set-up-https-locally-with-create-react-app/

你可能感兴趣的:(java,python,https,docker,linux)