2017-08-10 28 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