2017-08-10 30 views
1

我试图中继GET请求,因此当用户向服务器发送POST请求时,服务器会对另一个URL执行另一个GET请求并返回结果。Sinatra POST中的Ruby Http gem(http客户端)

问题是,当我用puts打印结果时,我看到了我期待的正确结果,但最后一行(我相信ruby函数的最后一行自动返回)不会响应POST请求(它返回空的响应)。来自JavaScript我相信它正在做一个异步的GET调用,并且响应不等待,直到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 

回答

2

更改

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方法返回一个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