【问题标题】:OpenWeathermap country codes code problem "city not found"OpenWeathermap 国家代码问题“未找到城市”
【发布时间】:2022-01-24 19:49:55
【问题描述】:

我正在为天气日志应用程序编写代码。问题是,当我将 openweathermap.com 网站的 URL 传递给 fetch 方法时,它使用邮政编码和国家/地区代码方式,它只接受国家/地区代码,因为美国它从不接受另一个国家/地区。我尝试了很多,但它从不接受其中任何一个,它只将预测的数据对象返回到美国,而对于任何其他国家,它只显示消息未找到城市。这是我的代码:

const generate = document.getElementById('generate').addEventListener('click', function(){
    const zip = document.getElementById('zip').value;
    const countryCode = document.getElementById('countryCode').value;
    endPointData(zip,countryCode,apiKey);
})

const endPointData = async (zip,countryCode,apiKey) => {
    const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?zip=${zip},${countryCode}&appid=${apiKey}`);

    try{
        const data = await res.json();
        console.log(data);
    }
    catch(error){
        // appropriately handles the errors.
        console.log("error",error);
    }
}

const postData = async (url='', data = {}) => {
    const response = await fetch(url,{
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data),
    });
    try{
        const newData = await response.json();
        return newData;
    }catch(error){
        console.log("error",error);
    }
}

【问题讨论】:

    标签: javascript html css node.js server


    【解决方案1】:

    我在其他国家也可以正常工作。

    const apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    const zipCode = "110007";
    const countryCode = "IN";
    
    const endPointData = async (zipCode, countryCode, apiKey) => {
        const URL = `https://api.openweathermap.org/data/2.5/weather?zip=${zipCode},${countryCode}&appid=${apiKey}`;
    
        const res = await fetch(URL);
    
        try {
            const data = await res.json();
            console.log(data);
        }
        catch(error){
            // appropriately handles the errors.
            console.log("error",error);
        }
    }
    
    endPointData(zipCode, countryCode, apiKey);
    

    【讨论】:

      【解决方案2】:

      console.log 您的 URL 变量。也许你的国家代码是空的。 当未指定国家代码时,API 默认回退到美国。 https://openweathermap.org/current#zip

      先在邮递员那里试试 (https://www.postman.com/)!

      【讨论】:

        猜你喜欢
        • 2022-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 2017-10-20
        • 2011-01-14
        • 1970-01-01
        相关资源
        最近更新 更多