【问题标题】:faraday builder use multixml to parse bodyfaraday builder使用multixml解析body
【发布时间】:2014-04-24 00:05:42
【问题描述】:

我想设置 faraday 使用 multi_xml 并默认解析我的响应正文。

@connection = Faraday.new(base_url) {|builder| builder.response :xml, content_type: /xml/}

导致:

NoMethodError: undefined method `[]' for nil:NilClass
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday_middleware-0.9.1/lib/faraday_middleware/response_middleware.rb:59:in `response_type'
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday_middleware-0.9.1/lib/faraday_middleware/response_middleware.rb:31:in `block in call'
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday-0.9.0/lib/faraday/response.rb:57:in `on_complete'
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday_middleware-0.9.1/lib/faraday_middleware/response_middleware.rb:30:in `call'
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday-0.9.0/lib/faraday/rack_builder.rb:139:in `build_response'
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday-0.9.0/lib/faraday/connection.rb:377:in `run_request'
from /Users/blanecordes/.rvm/gems/ruby-2.0.0-p353@can/gems/faraday-0.9.0/lib/faraday/connection.rb:177:in `post'

gem 中的第 59 行:

 def response_type(env)
  type = env[:response_headers][CONTENT_TYPE].to_s
  type = type.split(';', 2).first if type.index(';')
  type
end

【问题讨论】:

  • 如果你使用content_type: /\bxml$/。另外,您能否curl 该 HTTP 路径并看到您确实收到了响应?
  • @cevaris 我在使用 /\bxml$/ 时得到了相同的响应 我在删除构建器块时得到了响应,所以它与此有关

标签: ruby-on-rails ruby xml faraday


【解决方案1】:

尝试像这样将构建器变量移到块之外...

@connection = Faraday.new(base_url) do |builder| 
   builder.response :xml, content_type: /xml/
end

这是一个似乎对我有用的例子。

require 'faraday'
require 'faraday_middleware'
require 'pp'

base_url = 'http://www.w3schools.com/xml/note.xml'
@connection = Faraday.new(base_url) do |builder| 
   builder.response :xml,  :content_type => /\bxml$/
end
pp @connection

【讨论】:

  • gem 中的第 59 行是 def response_type(env) type = env[:response_headers][CONTENT_TYPE].to_s type = type.split(';', 2).first if type.index( ';') 类型结束
  • 只是假设,但是您使用的是 gem faraday_middleware 吗?如果是这样,我只是使用它更新了我的答案。
【解决方案2】:

遇到的错误是由缺少适配器声明引起的。你必须把它放在构建器块的末尾。

require 'faraday'
require 'faraday_middleware'

@connection = Faraday.new(base_url) do |builder|
  builder.response :xml, content_type: /\bxml$/
  builder.adapter Faraday.default_adapter
end

见:faraday_middleware's wiki

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-02
    • 2016-07-25
    • 2016-10-14
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多