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.