OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

In my Vite/React project, I'm having trouble implementing an environment variable for my Openweather API key

  • Thread starter Thread starter mjshubham21
  • Start date Start date
M

mjshubham21

Guest
I have an .env file in my root folder of the project. I checked the API key and it is correct and I used the actual key in the URL instead of process.env.API_KEY and it fetched the data correctly

I'm using VITE and in my server.js file I've got this line:

Code:
const apiKey = process.env.API_KEY;

This is my function for getting the data:

Code:
const apiKey = import.meta.env.VITE_API_KEY;
const getData = (city) => {
    if (!city) return;
    const apiURL =
      "https://api.openweathermap.org/data/2.5/weather?q=" +
      city +
      "&units=metric&appid=" +
      apiKey;
    axios
      .get(apiURL)
      .then((res) => {
        console.log("Response: ", res.data);
        setData(res.data);
      })
      .catch((err) => {
        console.log("Error: ", err);
      });
  };

I'm trying to implement environment variables in my weather component in order to hide my API key. I want to fetch the weather details using the API key from my .env file.

<p>I have an <code>.env</code> file in my root folder of the project.
I checked the API key and it is correct and I used the actual key in the URL instead of <code>process.env.API_KEY</code> and it fetched the data correctly</p>
<p>I'm using VITE and in my <code>server.js</code> file I've got this line:</p>
<pre><code>const apiKey = process.env.API_KEY;
</code></pre>
<p>This is my function for getting the data:</p>
<pre class="lang-js prettyprint-override"><code>const apiKey = import.meta.env.VITE_API_KEY;
const getData = (city) => {
if (!city) return;
const apiURL =
"https://api.openweathermap.org/data/2.5/weather?q=" +
city +
"&units=metric&appid=" +
apiKey;
axios
.get(apiURL)
.then((res) => {
console.log("Response: ", res.data);
setData(res.data);
})
.catch((err) => {
console.log("Error: ", err);
});
};
</code></pre>
<p>I'm trying to implement environment variables in my weather component in order to hide my API key. I want to fetch the weather details using the API key from my <code>.env</code> file.</p>
 

Latest posts

B
Replies
0
Views
1
Blundering Ecologist
B
Top