[英]Why does Create React App .env for api keys doesn't work when uploaded to AWS Amplify
I added a dotenv file for an api key in my react app, i followed this tutorial: https://www.pluralsight.com/guides/hiding-secret-keys-in-create-react-app as well as this: https://create-react-app.dev/docs/adding-custom-environment-variables/ I prefixed it as REACT_APP_API_KEY.我在我的反应应用程序中为 api 密钥添加了一个 dotenv 文件,我遵循了本教程: https ://www.pluralsight.com/guides/hiding-secret-keys-in-create-react-app 以及这个: https ://create-react-app.dev/docs/adding-custom-environment-variables/我给它加上前缀 REACT_APP_API_KEY。 The app works locally but not when uploaded to AWS.该应用程序在本地运行,但在上传到 AWS 时不起作用。
This the on load fetch:这是加载时获取:
useEffect(() => {
const fetchData = async () => {
try {
const url = `https://api.themoviedb.org/3/search/movie/?api_key=${process.env.REACT_APP_API_KEY}&language=en-US&query=all`;
const response = await fetch(url);
const data = await response.json();
setMovieList(data.results);
} catch (err) {
console.log(err);
}
};
fetchData();
}, []);
This the search submit button handler:这是搜索提交按钮处理程序:
const handleSearch = useCallback(async () => {
try {
const url = `https://api.themoviedb.org/3/search/movie/?api_key=${process.env.REACT_APP_API_KEY}&language=en-US&query=${query}&page=1&include_adult=false`;
const response = await fetch(url);
const jsondata = await response.json();
await setMovies(jsondata.results);
} catch (err) {
console.log(err);
}
}, [query]);
Typically, whenever you deploy a React app created with Create React App (CRA), you run yarn build
and then upload the build
directory to some hosting solution.通常,每当您部署使用Create React App (CRA)创建的 React 应用程序时,您都会运行yarn build
,然后将build
目录上传到某个托管解决方案。 There is no actual process binary that you run (from React's perspective) after that.之后没有实际运行的进程二进制文件(从 React 的角度来看)。
During development, CRA's toolchain (Webpack dev server) is a running process and handles the actual serving and building of content which means it has access to the variables from .env
.在开发过程中,CRA 的工具链(Webpack 开发服务器)是一个正在运行的进程,负责处理内容的实际服务和构建,这意味着它可以访问.env
的变量。 Once you have run yarn build
, CRA is hands off and all the execution is handled by some other server that CRA is oblivious to.一旦你运行了yarn build
,CRA 就会放手,所有的执行都由 CRA 不知道的其他服务器处理。 Any variables that did exist are hard-injected into the built app at build time Referencing Environment Variables in the HTML .任何确实存在的变量都在构建时硬注入到构建的应用程序中, 引用 HTML 中的环境变量。
If you need these variables to change based on a deployment, you should have another .env
file that gets used in your build tools or make them regular environment variables available in your build script.如果您需要根据部署更改这些变量,您应该有另一个.env
文件用于您的构建工具或在您的构建脚本中使它们常规环境变量可用。 Just about every continuous deployment (CI) tool has this capability.几乎每个持续部署 (CI) 工具都具有此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.