ruby-on-rails - 为什么我的 API 请求使用 HTTParty 返回 400 响应?
问题描述
我正在创建一个简单的 Rails 应用程序,它从 Open Weather Map API 获取数据并返回在表单字段中搜索的城市的当前天气数据。例如,我希望 API 调用看起来像这样:
http://api.openweathermap.org/data/2.5/weather?q=berlin&APPID=111111
我已经在 Postman 中使用我的 API 密钥对其进行了测试,它工作正常,但使用我的代码返回"cod":"400","message":"Nothing to geocode"
谁能看到我哪里出错了?这是我的代码。
服务/open_weather_api.rb
class OpenWeatherApi
include HTTParty
base_uri "http://api.openweathermap.org"
def initialize(city = "Berlin,DE", appid = "111111")
@options = { query: { q: city, APPID: appid } }
end
def my_location_forecast
self.class.get("/data/2.5/weather", @options)
end
end
预测控制器.rb
class ForecastsController < ApplicationController
def current_weather
@forecast = OpenWeatherApi.new(@options).my_location_forecast
end
end
current_weather.html.erb
<%= form_tag(current_weather_forecasts_path, method: :get) do %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %><br>
<%= @forecast %>
路线.rb
Rails.application.routes.draw do
root 'forecasts#current_weather'
resources :forecasts do
collection do
get :current_weather
end
end
end
解决方案
该错误描述了自身:
"cod":"400","message":"Nothing to geocode"
这意味着您没有在查询中提供城市。此错误的一个可能原因是您在此行中使用来自控制器initialize
的变量覆盖了方法中的默认值:@options
class ForecastsController < ApplicationController
def current_weather
@forecast = OpenWeatherApi.new(@options).my_location_forecast
end
end
根据您提供的信息,您尚未@options
在控制器中定义变量,或者它是nil
. 所以这是覆盖initialize
方法的默认值OpenWeatherApi
。由于您案例中的 appid 不会更改,因此只有城市名称会更改,因此您可以从控制器发送它。
def current_weather
@city = params[:city] // the city you want to send to API. Change it with your value
@forecast = OpenWeatherApi.new(@city).my_location_forecast
end
推荐阅读
- arrays - 检查用户在数组中输入的元素的积极性
- algorithm - 如何将索引号添加到树的节点
- powershell - 我正在尝试从批处理脚本运行几个 PowerShell 命令,但是“%”符号没有被传输
- json - 如何使我的 VB.NET 代码动态而不是静态?
- php - 如果记录存在则查询数据库,如果不存在则回显答案
- function - 如何在 setState 之后保留先例小部件
- java - 为什么 MockMvc 测试建议注入 WebApplicationContext @BeforeEach 测试?
- c++ - 模板化省略号构造函数 C++
- python - 将DataFrame的每一行重复N次以创建一个新的DataFrame(N由另一列定义)
- python - 如何在条形图中从一列列表中绘制词频