我必须构建一个角度js应用程序作为客户端来使用api。 问题是api不支持jsonp调用。
所以我创建了一个rails应用程序来调用api并返回内容。 我正在使用faraday gem
现在我每次调用api都有一个方法。但由于每个方法只创建一个请求,因此触发请求并返回内容。
如果我可以创建一个代理控制器,根据它接收的内容创建请求,然后使用法拉第创建一个请求并返回结果,我就会徘徊。像这样:
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"]
端
这不起作用。我做错了什么? 它始终以
失败NoMethodError (undefined method `strip' for #<StringIO:0x3436848>):
app/controllers/api_proxy_controller.rb:7:in `proxy_request'
答案 0 :(得分:0)
回溯是不完整的(某些框架,例如Rails / RSpec,可能会隐藏默认情况下来自项目外部的行)。该错误实际上来自Net::HTTP
(net/http/header.rb:17
),至少在我的情况下(Ruby 2.1,Rails 4.0.2和默认的法拉第适配器)。它希望标头中的所有值都是字符串(或者至少响应strip
)。
一种解决方法是使用非字符串值排除任何标头。根据您的要求,这可能适用于您,也可能不适合您,例如类似的东西:
faraday_conn.run_request(
request.method_symbol,
request.fullpath,
request.body.read,
request.headers.select{|k,v| v.respond_to?(:strip)}
)
请注意,由于这是在Rails控制器中,request.headers
会返回ActionDispatch::Http::Headers
的实例,它会像Hash
一样嘎嘎作响但实际上并不是Hash
(您可以调用to_h
就可以将其转换为哈希值。