1

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.)

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.