当我提交到 github 时,我试图隐藏我的 API 密钥,并且我查看了论坛以获取指导,尤其是以下帖子:
如何在 create-react-app 中隐藏 API 密钥?
我进行了更改并重新启动了纱线。我不确定自己做错了什么——我在项目的根目录中添加了一个 .env
文件(我将其命名为 process.env
)并在我刚刚放入的文件中 REACT_APP_API_KEY = 'my-secret-api-key'
。
我想这可能是我在 App.js 中将密钥添加到我的 fetch
的方式,并且我尝试了多种格式,包括不使用模板文字,但我的项目仍然不会编译。
任何帮助深表感谢。
performSearch = (query = 'germany') => {
fetch(`https://api.unsplash.com/search/photos?query=${query}&client_id=${REACT_APP_API_KEY}`)
.then(response => response.json())
.then(responseData => {
this.setState({
results: responseData.results,
loading: false
});
})
.catch(error => {
console.log('Error fetching and parsing data', error);
});
}
原文由 Biii 发布,翻译遵循 CC BY-SA 4.0 许可协议
4个步骤
npm install dotenv --save
接下来将以下行添加到您的应用程序中。
require('dotenv').config()
.env
文件并将变量添加到其中。.env
添加到您的.gitignore
文件中,以便 Git 忽略它并且它永远不会出现在 GitHub 上。如果您使用的是 create-react-app ,那么您只需要第 3 步和第 4 步,但请记住变量需要以
REACT_APP_
开头才能正常工作。参考: https ://create-react-app.dev/docs/adding-custom-environment-variables/
注意- 在 .env 文件中添加变量后需要重新启动应用程序。
参考 - https://medium.com/@thejasonfile/using-dotenv-package-to-create-environment-variables-33da4ac4ea8f