How do I get Rails to parse a published string as json without sending a Content-type: application / json header?

Rails changes the behavior at several levels when sending the header "Content-type: application / json":

  • The submitted message body is parsed as json instead of a string parameter
  • wrap_parameters: format => [: json] in config / initializers / wrap_parameters.rb is used when parsing sent the mentioned parameters (so that you can either send json with or without the root element)

What if I cannot trust the (external) client when passing the correct header? In other words, I want my application to behave as if the client always passes the Content-type: application / json header, even if the client does not actually?

+6
source share
1 answer

You can set the type inside the action with

request.format = :json 

I tested it using

 class ExampleController < ApplicationController def always_accept_json request.format = :json respond_to do |format| format.json { raise "HEY" } format.html end end end 

What can you do in any ActionController, i.e. if you want at the top level that the entire request appears in your application as content_type application/json , just make it a filter on application_controller.rb that sets request.format

+1
source

Source: https://habr.com/ru/post/927844/


All Articles