我正在尝试将一些代码从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自动将我的请求体序列化为字符串吗?
发布于 2015-04-11 09:11:36
中间件列表要求按照特定的顺序构造/堆叠,否则将遇到此错误。第一个中间件被认为是最外层的,它封装了所有其他中间件,因此适配器应该是最内部的(或最后一个):
Faraday.new(url: "http://localhost") do |config|
config.request :json
config.response :json
config.adapter Faraday.default_adapter
end
有关其他信息,请参见高级中间件使用。
发布于 2015-04-08 13:38:12
您可以始终为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"
https://stackoverflow.com/questions/29440768
复制相似问题