【发布时间】:2019-10-06 01:30:22
【问题描述】:
我正在尝试使用同名的gem 调用开放天气地图 API。我正在尝试获取一个城市的当前预测。我查看了他们的常见问题解答,但无法解决。当我尝试加载 http://localhost:3000/forecasts/berlin_weather 时返回:Berlin forecast: {"cod"=>401, "message"=>"Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."} 这表明它正在连接,但不确定为什么我没有得到预期的响应。这是我的代码。
服务/open_weather_api.rb
class OpenWeatherApi
require 'open_weather'
def initialize(city, appid = "blahblahblah", units = "metric")
@options = { city: city, units: units, APPID: appid }
end
def berlin_forecast
OpenWeather::Forecast.city(@options)
end
end
forecasts_controller.rb
class ForecastsController < ApplicationController
def berlin_weather
@forecast = OpenWeatherApi.new("Berlin").berlin_forecast
end
end
berlin_weather.html.erb
<p>Berlin forecast: <%= @forecast %></p>
【问题讨论】:
-
是否正在设置 API 密钥,就像错误消息所暗示的那样?
-
@bo-oz 是的,API 密钥已在我的服务类中设置。一旦我开始工作,就会将它添加到加密的凭据中。
-
我会向 gem 作者打开一个问题,可能 API 中发生了一些变化。查看 Open Weathers API 文档并将其与 gem 的功能进行比较。
标签: ruby-on-rails openweathermap