2015-04-03 114 views
4

我试图将一些代码从HTTParty转换为Faraday。以前我是用:Faraday JSON发布'undefined method bytesize'for have bodies

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。法拉第能够自动将我的请求主体序列化为字符串吗?

+1

尝试将适配器放在中间件列表中 - 请参阅[高级中间件用法](https://github.com/lostisland/faraday)。 – 2015-04-08 04:19:02

+0

@ l'L'l这绝对是错误。你可以添加一个答案,而不是评论,所以我可以接受+赏金? – 2015-04-10 23:16:36

回答

3

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

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

,了解更多信息,请参阅Advanced middleware usage

+1

谢谢!这绝对是有序的。欣赏回应。 – 2015-04-13 21:57:58

-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" 
+0

你为什么投下来?使用自己的中间件,您可以轻松地进行序列化。 – dolgishev 2015-04-08 19:31:41

+2

我投了票,因为这是一个不好的解决方案。 @我想我的评论是正确的解决方案。编写自定义中间件来解决参数排序问题(这是唯一的问题)的建议是荒谬的。 – 2015-04-10 23:19:11