Sinatra doesn't show POST data

懵懂的女人 提交于 2019-12-11 08:22:54

问题


I am making AJAX request from the client to Sinatra but somehow the data doesn't show up.Chrome request headers tab suggests that on the client side is everything OK:

Request Payload 
{ test: Data }

However, on Sinatra's side

  post '/api/check/:name' do
    sleep 3
    puts params.inspect
  end

And the console:

 127.0.0.1 - - [03/Feb/2014 10:45:53] "POST /api/check/name HTTP/1.1" 200 17 3.0019
    {"splat"=>[], "captures"=>["name"], "name"=>"name"}

Post data is nowhere to be found, what's wrong ?


回答1:


It's a common fault. Sinatra just parse form data (source).

To fix this use rack-contrib or the request.body.

Form parameter would look like this

curl -X POST 127.1:4567/ -d "foo=bar"

Instead of params you can just use request.body.read or use rack contrib.

rack-contrib

  1. Install it with gem install rack-contrib
  2. Require it

    require 'rack'

    require 'rack/contrib'

  3. Load it use Rack::PostBodyContentTypeParser

With this you can use params as normal for json post data. Something like this:

curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' 127.1:4567/

Source for this:

  • Sinatra controller params method coming in empty on JSON post request,
  • http://jaywiggins.com/2010/03/using-rack-middleware-to-parse-json/


来源:https://stackoverflow.com/questions/21524020/sinatra-doesnt-show-post-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!