简体   繁体   English

如何在使用 yarn 和 vite 设置的 React 应用程序中使用 process.env 访问 API 密钥

[英]How to use process.env to access API key in React app set up with yarn and vite

I'm trying to build an e-commerce app and I have used yarn create vite to begin my app build.我正在尝试构建一个电子商务应用程序,并且我已经使用yarn create vite开始我的应用程序构建。

I'm trying to store my API key and url in a.env file.我正在尝试将我的 API 密钥和 url 存储在 a.env 文件中。

I'm attempting to access the variables in the.env file using this code:我正在尝试使用以下代码访问 .env 文件中的变量:

   useEffect(() => {
      const fetchData = async () => {
         try {
            const data = await axios.get(
               process.env.REACT_APP_API_URL + "/products",
               {
                  headers: {
                     Authorization: "bearer" + process.env.REACT_APP_API_TOKEN,
                  },
               }
            )
            console.log(data)
         } catch (err) {
            console.log(err)
         }
      }
      fetchData()
   }, [])

When I open the console in the browser, I am getting the following error:当我在浏览器中打开控制台时,出现以下错误:

ReferenceError: process is not defined ReferenceError:进程未定义

Any idea on how I can define process to use process.env to access the API variables?关于如何定义流程以使用 process.env 访问 API 变量的任何想法?

Reading the documentation provided by clxrity.阅读 clxrity 提供的文档。 I changed code and variable names to what is shown below and everything worked fine:我将代码和变量名更改为如下所示,一切正常:

 useEffect(() => {
  const fetchData = async () => {
     try {
        const data = await axios.get(
           `${import.meta.env.VITE_APP_API_URL}/products`,
           {
              headers: {
                 Authorization: `bearer ${
                    import.meta.env.VITE_APP_API_TOKEN
                 }`,
              },
           }
        )
        console.log(data)
     } catch (err) {
        console.log(err)
     }
  }
  fetchData()

}, []) }, [])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM