我正在尝试调试Rails没有解码JSON POST数据的问题。
服务器日志显示:
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值。在我写一个尝试JSON.parse所有params键的before_filter之前,有没有人有任何想法?
我不认为这是相关的,因为我发送和接收数据没问题,但是在IE的CORS请求期间(使用XDomainRequest)会出现此问题。
答案 0 :(得分:17)
您可以通过将Content-Type标头设置为“application / json”来解决此问题。您可以让Accept控制器知道它希望返回什么,并将Accept标头设置为“application / json”。
以下两个标题的命令:
curl -d '{ "company": { "name": "acme", "address": "123 Carrot Street" } }' http://0.0.0.0:3000/mysite --header "Accept: application/json" --header "Content-Type: application/json"
在日志中生成:
Started POST "/mysite" for 127.0.0.1 at 2012-01-11 16:09:48 -0800
Processing by MyController#create as JSON
Parameters: {"company"=>{"name"=>"acme", "address"=>"123 Carrot Street"}, "wassup"=>{"company"=>{"name"=>"acme", "address"=>"123 Carrot Street"}, "controller"=>"wassup", "action"=>"create"}}
Completed 200 OK in 5ms (Views: 2.0ms | ActiveRecord: 0.0ms)
此命令带有Accept标头:
curl -d '{ "company": { "name": "acme", "address": "123 Carrot Street" } }' http://0.0.0.0:3000/mysite --header "Accept: application/json"
生成这些日志:
Started POST "/mysite" for 127.0.0.1 at 2012-01-11 16:07:26 -0800
Processing by MyController#create as JSON
Parameters: {"{ \"company\": { \"name\": \"acme\", \"address\": \"123 Carrot Street\" } }"=>nil}
Completed 200 OK in 7ms (Views: 5.0ms | ActiveRecord: 0.0ms)
最后这个命令带有Content-Type标题:
curl -d '{ "company": { "name": "acme", "address": "123 Carrot Street" } }' http://0.0.0.0:3000/mysite --header "Content-Type: application/json"
生成这些日志:
Started POST "/mysite" for 127.0.0.1 at 2012-01-11 16:08:11 -0800
Processing by MyController#create as */*
Parameters: {"company"=>{"name"=>"acme", "address"=>"123 Carrot Street"}, "wassup"=>{"company"=>{"name"=>"acme", "address"=>"123 Carrot Street"}, "controller"=>"wassup", "action"=>"create"}}
Completed 200 OK in 4ms (Views: 2.0ms | ActiveRecord: 0.0ms)
请注意,已解析的参数和处理消息会随着每种标题类型而细微变化。
答案 1 :(得分:9)
before_filter :fix_ie_params, only: [:create, :update]
精简:
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
对于独角兽和 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