问题
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
- Install it with
gem install rack-contrib
require it
require 'rack'
require 'rack/contrib'
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