5

我正在尝试将一些代码HTTPartyFaraday. 以前我使用的是:

HTTParty.post("http://localhost/widgets.json", body: { name: "Widget" })

新的片段是:

faraday = Faraday.new(url: "http://localhost") do |config|
  config.adapter Faraday.default_adapter

  config.request :json
  config.response :json
end
faraday.post("/widgets.json", { name: "Widget" })

这导致:NoMethodError: undefined method 'bytesize' for {}:Hash。是否可以让法拉第自动将我的请求正文序列化为字符串?

4

2 回答 2

5

中间件列表要求它按特定顺序构建/堆叠,否则您将遇到此错误。第一个中间件被认为是最外面的,它包装了所有其他中间件,因此适配器应该是最里面的一个(或最后一个):

Faraday.new(url: "http://localhost") do |config|
  config.request :json
  config.response :json
  config.adapter Faraday.default_adapter
end

有关更多信息,请参阅高级中间件使用

于 2015-04-11T09:11:36.577 回答
-1

您始终可以为 Faraday 创建自己的中间件。

require 'faraday'

class RequestFormatterMiddleware < Faraday::Middleware
  def call(env)
    env = format_body(env)
    @app.call(env)
  end

  def format_body(env)
    env.body = 'test' #here is any of needed operation
    env
  end
end

conn = Faraday.new("http://localhost") do |c|
  c.use RequestFormatterMiddleware
end

response = conn.post do |req|
 req.url "http://localhost"
 req.headers['Content-Type'] = 'application/json'
 req.body = '{ "name": "lalalal" }' 
end

p response.body #=> "test"
于 2015-04-08T13:38:12.830 回答