Reputation: 3188
Does anyone know how to perform delegate extaral apis request to rails server instead of doing them in client side in a generic way?
This is needed in order to avoid Cross Domain requests on client side (http://0.0.0.0:3000 is not allowed by Access-Control-Allow-Origin.)
Upvotes: 1
Views: 123
Reputation: 3188
I found a very easy way to do this using Globbing Routes!
In the router:
match "api/*url" => "tunnel_api#tunnel_request", via: [:all]
And create the controller:
class TunnelApiController < ApplicationController
def tunnel_request
query_params_string = "?"
params.each do |key, value|
unless ((key == "controller") || (key == "action") || (key == "url"))
query_params_string += key + "=" + value + "&"
end
end
query_params_string = query_params_string[0..-2]
uri = URI.parse("external_host_url_with_ssl" + params[:url] + query_params_string)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
response = http.request(Net::HTTP::Get.new(uri.request_uri))
render json: response.body, status: 200
end
end
The tricky part is how to include the query params in the request, so here you can see the loop that I used for creating the query_params_string. Also remember to handle the different HTTP methods (POST, OPTIONS, …)
I've created a post in my blog for this: http://blog.tcit.cl/post/112616639620/rails-and-angularjs-with-external-api
Upvotes: 1