简体   繁体   中英

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.

I'm trying to store my API key and url in a.env file.

I'm attempting to access the variables in the.env file using this code:

   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

Any idea on how I can define process to use process.env to access the API variables?

Reading the documentation provided by 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()

}, [])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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