Faraday JSON post 'undefined bytesize' for method has bodies

I am trying to convert code from HTTPartyto Faraday. I used to use:

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

New snippet:

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" })

Result: NoMethodError: undefined method 'bytesize' for {}:Hash. Is it possible that Faraday automatically serializes the request body into a string?

+4
source share
2 answers

The middleware list requires it to be designed / stacked in a specific order, otherwise you will encounter this error. The first middleware is considered the most external, which wraps everything else, so the adapter must be the most internal (or the last):

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

. .

+3

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"
-1

All Articles