2

I'm doing a simple weather app and I'm trying to set my API key as an environment variable like you would in Python using apiKey = os.getenv['MY_API_KEY']. I'm having trouble getting the API key to work, even through using dotenv and browserify. When I run index.html and inspect the console it always says Reference Error: require not defined.

index.html

<body>
    <form action="weather.js" id="userForm" method="GET">
        <label for="city">City:</label>
        <input type="text" id="city" name="city" placeholder="Enter your city"><br>
        <label for="state">State:</label>
        <select id="state" name="state">
            <option value="AL">Alabama</option>
            ...
            <option value="WY">Wyoming</option>
        </select><br>
        <input type="button" id="submit" value="Get Weather!">
    </form>

    <div class="display">
         <h1 class="name"></h1>
         <p class="desc"></p>
         <p class="temp"></p>
    </div>

    <script src="weather.js"></script>
    <!-- ^^^ I've replaced this with bundle.js per the dotenv docs as well -->
</body>

weather.js

require('dotenv').config();

var button = document.querySelector('#submit');
var city = document.querySelector('#city');
var state = document.querySelector('#state');
var namee = document.querySelector('.name');
var desc = document.querySelector('.desc');
var temp = document.querySelector('.temp');
const apiKey = process.env.WEATHER_KEY

button.addEventListener('click',function(){
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+city.value+','+state.value+
    ',US&units=imperial&appid='+apiKey)
    .then(response => response.json())
    .then(data => {
        var nameValue = data['name'];
        var tempValue = data['main']['temp'];
        var descValue = data['weather'][0]['description'];

        namee.innerHTML = nameValue;
        temp.innerHTML = tempValue;
        desc.innerHTML = descValue;
    })

    .catch(err => alert('Wrong city name!'))
})

I understand why using require wouldn't normally work but I'm confused why it's not working with browserify.

2
  • Does this help you? Commented Jan 5, 2021 at 6:27
  • @3174N Sorta! I'm not getting the error anymore but when the app tries to make the API call, it is not setting const apiKey to the environment variable i set in my .env and returning undefined instead Commented Jan 6, 2021 at 3:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.