【问题标题】:Weather API (RESTful) giving error天气 API(RESTful)给出错误
【发布时间】:2021-03-29 20:42:17
【问题描述】:

我正在使用一个简单的 Web API 来获取城市 伦敦 的天气详细信息。但是,我没有得到所需的响应,而是 401 错误。我做错什么了吗?

HTML

<html> 
<head> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
<script>
$(document).ready(function(){
    $('button').click(function(){
        $.ajax({
            type: "get",
            url: "http://api.openweathermap.org/data/2.5/weather?q=London",
            dataType: "json",
            contentType: 'application/json',
            success: function(data) {
                    //What to do on success 
            }
        });
    });
});
</script> 
</head> 

<body>
    <button>Click Me</button>
</body> 

</html> 

使用以下 api

http://openweathermap.org/current

错误

【问题讨论】:

  • 调用该 URL 我得到以下响应:{"cod":401, "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."} 您是否在请求中传递了有效的 API 密钥? openweathermap.org/faq#error401
  • 请参阅所附页面和文档。我只从那里选择了网址。
  • 文档声明您需要有一个 API 密钥才能使用它:openweathermap.org/appid。另请注意,在免费帐户上,您调用 API 的次数受到限制。如果您的网站需要依赖此服务,我建议您支付 SLA
  • 是的,我现在明白了。我拿到了钥匙……现在再试一次。
  • 我有一个钥匙说:12345。现在你能告诉如何通过它吗?

标签: jquery web-services rest asp.net-web-api


【解决方案1】:

您需要将键作为查询字符串添加到天气 API 的 URL。

你可以添加一个小函数来做到这一点:

var url = 'http://api.openweathermap.org/data/2.5/forecast/city';
var keys = {
    id: 524901,
    APPID: 12345 // Put your key here
}; 

function makeUrl (url, queryStringObject) {
    var query = [];
    // Loops through each key
    for(var key in queryStringObject){
        query.push(encodeURIComponent(key) + '=' +
            encodeURIComponent(queryStringObject[key]));
    }
    // Returns the url with the keys appended
    return url + (query.length ? '?' + query.join('&') : '');
}

这将返回 api 所需格式的密钥:

http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=12345 

那么在你对api的调用中,就可以使用函数调用了:

$(document).ready(function(){
    $('button').click(function(){
        $.ajax({
            type: "get",
            url: makeUrl(url, keys), // Gets the constructed url
            dataType: "json",
            contentType: 'application/json',
            success: function(data) {
                    //What to do on success 
            }
        });
    });
});

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2017-05-04
    • 2021-07-07
    • 2022-10-07
    • 1970-01-01
    • 2017-06-14
    • 2017-12-12
    • 2011-12-09
    • 2021-11-09
    相关资源
    最近更新 更多