英文:
Issues accessing variables from .env file
问题
我一直在尝试从我的位于 Vite 应用根目录下的 .env 文件中获取 API 密钥,然后传递到 JSX 文件中进行数据获取,但每次我使用 `process.env.{MY_VARIABLE_NAME}` 时,浏览器控制台会返回一个错误:
> ReferenceError: process is not defined
我尝试过安装 dotenv,但仍然不起作用。
是否有人可以提供帮助?如果需要更多信息,我可以提供。
英文:
I have been trying to get my API key from my .env file that is at the root of my folder of my Vite app to a JSX file where I want to do the fetching, but each time I use process.env.{MY_VARIABLE_NAME}
the browser console returns an error:
> ReferenceError: process is not defined
The line where I am trying to get data from the API:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const api = await axios.get(`https://api.spoonacular.com/recipes/random?apikey=${process.env.RECIPE_API_KEY}`)
<!-- end snippet -->
I checked around and I have tried installing dotenv and it still not works
Can anyone help with this, and if there is any more information that will be needed, I am available to provide it.
答案1
得分: 1
"The process object is not available in the client side javascript environment, if you were running this on server side runtime it would work." 的中文翻译如下:
"在客户端 JavaScript 环境中,process 对象不可用。如果您在服务器端运行它,它将正常工作。"
英文:
The process object is not available in the client side javascript environment, if you were running this on server side runtime it would work.
答案2
得分: 1
你可以尝试将其赋值给变量,然后使用它:
const API= process.env.RECIPE_API_KEY;
const api = await axios.get(`https://api.spoonacular.com/recipes/random?apikey=${API}`)
我认为这会起作用。
英文:
You may try by assigning it to the variable and then use it as:
const API= process.env.RECIPE_API_KEY;
const api = await axios.get(`https://api.spoonacular.com/recipes/random?apikey=${API}`)
I think this will work
答案3
得分: 1
如果你没有使用React应用或类似Webpack的打包工具,并且希望在客户端直接使用环境变量而无需任何构建过程,你可以在服务器响应中暴露环境变量,并在客户端的JavaScript代码中访问它们。
英文:
If you're not using a React app or a bundler like Webpack, and you want to use environment variables directly on the client side without any build process, you can expose the environment variables in your server's response and access them in your client-side JavaScript code.
答案4
得分: 0
在做了一些研究后,我发现,由于我正在使用 Vite React 应用程序,要访问 .env 文件中的变量,应该使用 `import.meta.env.{MY_VARIABLE_NAME}` 而不是 `process.env`。
而且,我必须在我的 .env 文件和尝试访问 API 密钥的地方的变量名前加上 VITE_ 前缀。
英文:
After doing some research, I found out that, since I am using a Vite React app, to access the variables in the .env file import.meta.env.{MY_VARIABLE_NAME}
should be used instead of process.env
.
And my I have to add a VITE_ prefix to the start of the variable name in both my .env file and where I am trying to access the API key.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论