如何解决React中用于API的环境问题?

huangapple go评论69阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月21日 00:31:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75792920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定