我试图隐藏我的API密钥,当我提交到GitHub,我已经通过论坛的指导,特别是下面的帖子:

我如何隐藏一个API密钥在创建反应应用程序?

我做了修改并重新启动Yarn。我不确定我做错了什么-我添加了一个。env文件到我的项目的根(我命名为process.env),在文件中我只是把REACT_APP_API_KEY = 'my-secret-api-key'。

我想这可能是我在App.js中添加关键字的方式,我尝试了多种格式,包括不使用模板文字,但我的项目仍然不会编译。

performSearch = (query = 'germany') => { 查询https://api.unsplash.com/search/photos?query=获取(“$ {}client_id = $ {REACT_APP_API_KEY}’) .then(response => response.json()) .then(responseData => { this.setState ({ 结果:responseData.results, 加载:假 }); }) .catch(error => { console.log('读取和解析数据出错',Error); }); }


当前回答

设置好环境变量后,必须再次运行npm start。这就是我所缺少的部分。在自动重新加载时,.env变量不会更新。

其他回答

你必须安装npm install env-cmd

在根目录中创建.env并像这样更新& REACT_APP_是变量名的强制前缀。

REACT_APP_NODE_ENV="production"
REACT_APP_DB="http://localhost:5000"

更新package.json

  "scripts": {
    "start": "env-cmd react-scripts start",
    "build": "env-cmd react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  }

1. 在根文件夹上创建.env文件

有些源代码更喜欢使用.env.development和.env。生产,但这不是强制性的。

2. 变量的名称必须以REACT_APP_YOURVARIABLENAME开头

似乎如果您的环境变量不是这样开始的,您就会遇到问题。

3.包括你的变量

要包含环境变量,只需输入process.env。代码中的REACT_APP_VARIABLE。

您不必安装任何外部依赖项

该解决方案不需要任何额外的包。

步骤1 ReactDocs

在上面的文档中,他们提到了在Shell中导出和其他选项,而我将尝试解释的是使用.env文件

1.1创建Root/.env

#.env file
REACT_APP_SECRET_NAME=secretvaluehere123

重要提示:它必须以REACT_APP_开头。

1.2访问ENV变量

# App.js file or the file you need to access ENV
<p>print env secret to HTML</p>
<pre>{process.env.REACT_APP_SECRET_NAME}</pre>

handleFetchData() { // access in API call
  fetch(`https://awesome.api.io?api-key=${process.env.REACT_APP_SECRET_NAME}`)
    .then((res) => res.json())
    .then((data) => console.log(data))
}

1.3构建环境问题

在我执行步骤1.1|2后,它不起作用,但随后我发现了上述问题/解决方案。React在构建时读取/创建env,因此每次修改.env文件时都需要运行npm run start,以便更新变量。

Install dotenv as devDependencies: npm i --save-dev dotenv Create a .env file in the root directory: my-react-app/ |- node-modules/ |- public/ |- src/ |- .env |- .gitignore |- package.json |- package.lock.json. |- README.md Update the .env file like below & REACT_APP_ is the compulsory prefix for the variable name. REACT_APP_BASE_URL=http://localhost:8000 REACT_APP_API_KEY=YOUR-API-KEY [ Optional but Good Practice ] Now you can create a configuration file to store the variables and export the variable so can use it from others file. For example, I've create a file named base.js and update it like below: export const BASE_URL = process.env.REACT_APP_BASE_URL; export const API_KEY = process.env.REACT_APP_API_KEY; Or you can simply just call the environment variable in your JS file in the following way: process.env.REACT_APP_BASE_URL

如果你得到的值是未定义的,那么你应该考虑重新启动Node.js服务器并重新编译。