英文:
How can I resolve an env issue in React for API use?
问题
以下是您要翻译的代码部分:
我正在尝试从API请求数据,但出现以下错误:
Uncaught (in promise) ReferenceError: process is not defined
这是我的代码:
const getPopular = async () => {
const api = await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`);
const data = await api.json();
console.log(data);
}
我确保.env文件位于/src文件夹之外,确保密钥正确,重启了服务器,确保REACT_APP_API_KEY正确编写,当我将`${process.env.REACT_APP_API_KEY}`替换为实际密钥时,它正常运行。那么我漏掉了什么?
英文:
I'm trying to request data from an an api and it throws me the following error:
Uncaught (in promise) ReferenceError: process is not defined
Her's my code
const getPopular = async () => {
const api = await fetch (`https://api.spoonacular.com/recipes/random?apiKey=${process.env.REACT_APP_API_KEY}&number=9`)
const data = await api.json();
console.log(data);
}
I've made sure that the env file is outside the /src
folder, I've made sure the key is correct, I've restarted the server, I've made sure REACT_APP_API_KEY
is correctly written, And also it works fine when I replace ${process.env.REACT_APP_API_KEY}
with the actual key. So what am I missing?
答案1
得分: 0
Sure, here is the translated content:
"显然,在Vite中,环境变量(env's)的处理方式不同。
const getPopular = async () => {
const api = await fetch(`https://api.spoonacular.com/recipes/random?apiKey=${import.meta.env.VITE_APP_API_KEY}&number=9`)
const data = await api.json();
setPopular(data.recipes)
console.log(data);
}
.env
文件中的变量将以VITE_
前缀进行设置。
这就是诀窍。
感谢@ivanatias的帮助。"
英文:
Apparently, env's are handled differently in Vite
const getPopular = async () => {
const api = await fetch (`https://api.spoonacular.com/recipes/random?apiKey=${import.meta.env.VITE_APP_API_KEY}&number=9`)
const data = await api.json();
setPopular(data.recipes)
console.log(data);
}
And the variable in the .env
file will be prefixed with VITE_
And that does the trick.
Credits to @ivanatias for the help
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论