Faraday JSON post 'undefined method bytesize' 因为有物体

Faraday JSON post 'undefined method bytesize' for has bodies

我正在尝试将一些代码从 HTTParty 转换为 Faraday。以前我用的是:

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。是否可以让 Faraday 自动将我的请求主体序列化为字符串?

您始终可以为 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"

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

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

有关其他信息,请参阅 Advanced middleware usage