reading parameters on Sinatra post

China☆狼群 提交于 2019-12-31 03:19:08

问题


I'm working on my first Sinatra app and I have an hard time getting parameters from a post request.

I'm using MiniTest::Spec and my spec looks like

 payload = File.read("./spec/support/fixtures/payload.json")
 post "/api/v1/verify_payload", { payload: payload }, { "CONTENT_TYPE" => "application/json" } 
 last_response.body.must_eql payload

And this is my route

namespace '/api/v1' do
  post '/verify_payload' do
    MultiJson.load(params[:payload])
  end
end

The spec fails because last_response.body is empty.

Am I missing something here?

I also tried to return the entire params from verify_payload but also in that case it returned an empty string.

Update

curl -X POST -H "Content-Type: application/json" -d '{"payload":"xyz"}' http://localhost:9292/api/v1/verify_payload

does not return anything and no error on the server log

[2014-01-06 01:16:25] INFO  WEBrick::HTTPServer#start: pid=10449 port=9292
127.0.0.1 - - [06/Jan/2014 01:16:27] "POST /api/v1/verify_payload HTTP/1.1" 200 6 0.0220

Thanks


回答1:


Sinatra just don't parse this data, because they are no form parameters.

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/20932779/reading-parameters-on-sinatra-post

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