1

I have to built an angular js application as a client to consume the api. The problem is that the api doesn't support jsonp calls.

So I've created a rails application that makes the calls to the api and returns the content. I'm using the faraday gem

Right now I have a method for each call to the api. But since every method only creates a request, triggers the request and returns the content.

I'm was wandering if I can create a proxy controller that creates the request based on what it receives then creates an request with faraday and returns the result. Something like this :

 def proxy_request
    if request.method_symbol == :get || request.method_symbol == :delete
 line 7: response = faraday_conn.run_request(request.method_symbol, request.fullpath, nil, request.headers)
    elsif request.method_symbol == :post || request.method_symbol == :put || request.method_symbol == :patch
  response = faraday_conn.run_request(request.method_symbol, request.fullpath, request.body.read, request.headers)
end

render :text => response.body, :status => response.status, :content_type => response.headers["Content-Type"]

end

This is not working. What I'm doing wrong ? It always fails with

NoMethodError (undefined method `strip' for #<StringIO:0x3436848>):
app/controllers/api_proxy_controller.rb:7:in `proxy_request'
charlietfl
  • 170,828
  • 13
  • 121
  • 150
Mihai
  • 1,254
  • 2
  • 15
  • 27
  • I dropped angular tag as JS framework you use to consume data client side is completely irrelevant to issue – charlietfl Nov 03 '13 at 14:15

1 Answers1

0

The backtrace is incomplete (some frameworks, e.g. Rails/RSpec, may hide lines coming from outside your project by default). The error actually came from Net::HTTP (net/http/header.rb:17), at least in my case (Ruby 2.1, Rails 4.0.2 and the default Faraday adapter). It expects all values in headers to be strings (or at least respond to strip).

One workaround is to exclude any header with a non-string value. Depending on what you want to do, this may or may not work for you, e.g. something like:

faraday_conn.run_request(
  request.method_symbol,
  request.fullpath,
  request.body.read,
  request.headers.select{|k,v| v.respond_to?(:strip)}
)

Note that, since this is in a Rails controller, request.headers returns an instance of ActionDispatch::Http::Headers which quacks like a Hash but not actually a Hash (you can call to_h on it to convert it to a hash).