How to parse JSON request body in Sinatra just once and expose it to all routes?

前端 未结 5 1974
暗喜
暗喜 2020-12-15 16:12

I am writing an API and it receives a JSON payload as the request body.

To get at it currently, I am doing something like this:

post \'/doSomething\'         


        
5条回答
  •  醉酒成梦
    2020-12-15 16:21

    You can parse your JSON post body as a Hash with Rack::PostBodyContentTypeParser from https://github.com/rack/rack-contrib:

    require 'rack/contrib/post_body_content_type_parser'
    
    class Api < Sinatra::Application
      use Rack::PostBodyContentTypeParser
      ...
    end
    

    You can even pass a custom block to Rack::PostBodyContentTypeParser to parse the JSON as symbols instead of strings:

    a_proc = proc { |body| JSON.parse(body, symbolize_names: true, create_additions: false) }
    use Rack::PostBodyContentTypeParser, &a_proc
    

提交回复
热议问题