Reputation: 1570
I am trying to relay a GET
request so when the user does a POST
request to the server then the server does another GET
request to some other URL and returns the result.
The issue is that when I use puts
to print the result I see the correct result that I am expecting but the last line (I believe in ruby the last line of the function automatically returns) does not respond to the POST
request (it returns empty response). Coming from JavaScript I believe it is doing an asynchronous GET
call and POST
response is not waiting until GET
client is finished.
Any help would be appreciated.
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
Upvotes: 1
Views: 216
Reputation: 9177
Changes to
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
The HTTP.get
method returns a HTTP::Response
object rather than a String
object.
From the source code only specific types of object can be returned.
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
Upvotes: 2