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

穿精又带淫゛_ 提交于 2019-11-29 02:51:46

Use a sinatra before handler:

before do
  request.body.rewind
  @request_payload = JSON.parse request.body.read
end

this will expose it to the current request handler. If you want it exposed to all handlers, put it in a superclass and extend that class in your handlers.

You can also use Rack Middleware to parse it. See https://github.com/rack/rack-contrib Just use Rack::PostBodyContentTypeParser when initializing your Sinatra class.

Like this working for sinatra 1.4.5

before do
  if request.body.size > 0
    request.body.rewind
    @params = ActiveSupport::JSON.decode(request.body.read)
  end
end
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!