[英]Faraday gem undefined method 'bytesize'=' for Hash`
I want to send a POST request to an API.我想向 API 发送 POST 请求。 Here's my code:
这是我的代码:
conn = Faraday.new(url: BASE) do |faraday|
faraday.response :logger
faraday.request :url_encoded
faraday.headers['Content-Type'] = 'application/json'
faraday.headers["Authorization"] = "bearer #{AppConfig.instance.access_token}"
faraday.adapter Faraday.default_adapter
end
form_data = {a: 1, b: 2}
conn.post("/api/test", form_data)
But I get this error:但我收到此错误:
NoMethodError (undefined method `bytesize' for {:a=>1, :b=>2}:Hash)
I've also tried:我也试过:
conn.post("/api/test", form_data.to_json)
but it doesn't work either.但它也不起作用。
Official faraday repo provides next description:官方法拉第回购提供了下一个描述:
# post payload as JSON instead of "www-form-urlencoded" encoding:
conn.post do |req|
req.url '/nigiri'
req.headers['Content-Type'] = 'application/json'
req.body = '{ "name": "Unagi" }'
end
So, content type 'application/json' can't resolve hash.因此,内容类型“application/json”无法解析哈希。 Gem doesn't convert the body data to needed format by itself.
Gem 不会自行将 body 数据转换为所需的格式。
You need to convert your form_data to string( json
) format:您需要将 form_data 转换为 string(
json
) 格式:
form_data = {a: 1, b: 2}.to_json
Note.笔记。 Don't convert by
.to_s
when using symbol keys format because that will cause the parsing error.使用符号键格式时不要通过
.to_s
转换,因为这会导致解析错误。
With provided by you faraday configuration I can't cause any error after converting format_data to json.使用您提供的法拉第配置,将 format_data 转换为 json 后,我不会导致任何错误。 So, new error not related to faraday gem or provided code.
因此,新错误与法拉第 gem 或提供的代码无关。
Use to_json
to convert it to json, It fails with as_json
as well.使用
to_json
将其转换为 json,它也因as_json
而失败。
{ key: value }.as_json.respond_to?(:bytesize) => false
{ key: value }.to_json.respond_to?(:bytesize) => true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.