如何在 create-react-app 中隐藏 API 密钥? [英] How do I hide API key in create-react-app?
问题描述
我在 create-react-app 中制作了一个天气应用.如何隐藏 API 密钥以便我可以提交到 GitHub?
I made a weather app in create-react-app. How do I hide the API key so that I can commit to GitHub?
现在的关键是在 App.js 中:const API_KEY = "123456";
Right now the key is in App.js: const API_KEY = "123456";
推荐答案
不幸的是,在 React 客户端中保留任何密钥,即使您使用的是 gitignore 和 .env
文件,也是不安全的.正如@ClaudiuCreanga 所指出的,React 环境变量嵌入在构建中并且可以公开访问.
Unfortunately, keeping any key in your React client, even if you are using gitignore and an .env
file, is not secure. As pointed out by @ClaudiuCreanga, React environment variables are embedded in the build and are publicly accessible.
您真的应该只在后端(例如 Node/Express)中保存 API 密钥或机密.您可以让您的客户端向您的后端 API 发送请求,然后后端 API 可以使用 API 密钥进行实际的 API 调用,并将数据发送回您的客户端.
You should really only save API keys or secrets in your backend such as Node / Express. You can have your client send a request to your backend API, which can then make the actual API call with the API key and send the data back to your client.
这篇关于如何在 create-react-app 中隐藏 API 密钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!