在 Vanilla JS 中使用环境变量参考错误:需要未定义

问题描述

我正在开发一个简单的天气应用程序,我正在尝试将我的 API 密钥设置为环境变量,就像您在 Python 中使用 apiKey = os.getenv['MY_API_KEY'] 一样。即使使用 dotenv 和 browserify,我也无法使 API 密钥正常工作。当我运行 index.html 并检查控制台时,它总是显示 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!'))
})

我理解为什么使用 require 通常不起作用,但我很困惑为什么它不能与 browserify 一起使用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)