Rails JSON请求未正确解析为post参数 [英] Rails JSON request is not parsed correctly into post parameters
问题描述
我试图调试一个问题,其中Rails不解码JSON POST数据。
I'm trying to debug a problem where Rails isn't decoding the JSON POST data.
服务器日志显示:
2011-12-14T06:44:44+00:00 app[web.2]: Started POST
2011-12-14T06:44:44+00:00 app[web.2]: Processing by PostsController#create as */*
2011-12-14T06:44:44+00:00 app[web.2]: Parameters: {"{\"athlete_id\":\"\",\"known_as\":\"abc\",\"email\":\"abc@defg.com\",\"result\":\"112233\",\"rx\":false,\"mods\":\"thkjth\",\"notes\":\"\"}"=>nil, "affiliate_id"=>"testaffiliate", "wod_id"=>"12345"}
请注意,JSON字符串未被解析 - Rails将其指定为哈希中的键,指向nil值。有没有人在我写一个before_filter尝试JSON.parse所有的params键之前有任何想法?
Note that the JSON string is not being parsed - Rails is assigning it as a key in the hash, pointing to a nil value. Does anyone have any ideas before I write a before_filter that tries to JSON.parse all of the params keys?
我不认为这是相关的,因为我发送并接收数据,但是这个问题发生在来自IE的CORS请求(使用XDomainRequest)。
I don't think this is relevant since I'm sending and receiving data okay, but this problem occurs during a CORS Request from IE (using XDomainRequest).
推荐答案
before_filter :fix_ie_params, only: [:create, :update]
< ::
For Thin:
def fix_ie_params
if request.format == '*/*'
# try to JSON decode in case of IE XDR
begin
params.merge! ActiveSupport::JSON.decode(request.body.string)
rescue Exception=>e
# todo: log exception
end
end
end
Unicorn 和 Phusion Passenger
def fix_ie_params
if request.format == '*/*'
# try to JSON decode in case of IE XDR
begin
request.body.rewind
params.merge! ActiveSupport::JSON.decode(request.body.read)
rescue Exception=>e
# todo: log exception
end
end
end
这篇关于Rails JSON请求未正确解析为post参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!