Ruby Sinatra 中的 Http gem(http 客户端)POST

Ruby Http gem (http client) inside Sinatra POST

我正在尝试中继 GET 请求,因此当用户向服务器发出 POST 请求时,服务器会向其他 URL 发出另一个 GET 请求] 和 returns 结果。

问题是,当我使用 puts 打印结果时,我看到了我期望的正确结果,但最后一行(我相信 ruby 函数的最后一行自动returns) 不响应 POST 请求(它 returns 空响应)。来自 JavaScript 我相信它正在进行异步 GET 调用并且 POST 响应不会等到 GET 客户端完成。

如有任何帮助,我们将不胜感激。

require 'rubygems'
require 'sinatra'
require "http"

my_app_root = File.expand_path( File.dirname(__FILE__) + '/..' )

set :port, 80
set :bind, '0.0.0.0'
set :public_dir,   my_app_root + '/public'


post "/weather" do
  puts HTTP.get('https://www.metaweather.com/api/location/search/?query=milwaukee')  # prints correct result
  HTTP.get('https://www.metaweather.com/api/location/search/?query=milwaukee')       # response of POST method is empty string!
end

更改为

post "/weather" do
  puts HTTP.get('https://www.metaweather.com/api/location/search/?query=milwaukee')  # prints correct result
  HTTP.get('https://www.metaweather.com/api/location/search/?query=milwaukee').to_s
end

HTTP.get 方法 returns 一个 HTTP::Response 对象而不是 String 对象。


从源代码中只能返回特定类型的对象。

 res = [res] if Integer === res or String === res
  if Array === res and Integer === res.first
    res = res.dup
    status(res.shift)
    body(res.pop)
    headers(*res)
  elsif res.respond_to? :each
    body res
  end
  nil # avoid double setting the same response tuple twice