我正在尝试将一些代码从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
。是否可以让法拉第自动将我的请求主体序列化为字符串?
答案 0 :(得分:3)
中间件列表要求以特定顺序构造/堆叠,否则您将遇到此错误。第一个中间件被认为是最外层的,它包装了所有其他中间件,因此适配器应该是最里面的(或最后一个):
Faraday.new(url: "http://localhost") do |config|
config.request :json
config.response :json
config.adapter Faraday.default_adapter
end
有关其他信息,请参阅Advanced middleware usage。
答案 1 :(得分:-1)
您始终可以为法拉第创建自己的中间件。
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"