I have the following Sinatra code:
post '/bucket' do
# determine if this call is coming from filling out web form
is_html = request.content_type.to_s.downcase.eql?('application/x-www-form-urlencoded')
# If this is a curl call, then get the params differently
unless is_html
params = JSON.parse(request.env["rack.input"].read)
end
p params[:name]
end
If I call this using Curl, params has values, but when this is called via a web form, then params is nil and params[:name] has nothing. I spent several hours figuring out why it happens and asked help from other people, but no one could really find out what is going on.
One thing to note is, if I comment out this line:
params = JSON.parse(request.env["rack.input"].read)
then params has the correct value for “web-form” posting.
Actually, the goal is to get the params value if this code is being called by CURL call, so I used:
params = JSON.parse(request.env["rack.input"].read)
but it messed up the web-form posting. Can anyone solve this mystery?
Personally, I’d do it differently, by setting a hidden value in the form, something like:
then use it like:
If you see it you know the request came from your web-form. If
params['webform']doesn’t exist didn’t it came from Curl.I saved this to a file and ran it with Ruby:
Calling the running script using
http://localhost:4567/bucket?name=foodisplays:in the browser.
If I modify the source like:
restart it and load a simple HTML file:
and input
foobarand submit it, I see:in the browser window.
If I change the script to:
and restart Sinatra and resubmit the form, I see:
If I call it using Curl:
I see this on the command-line as Curl’s response:
If I change the script to:
restart the script, and call it with the Curl command again, I see:
on the command line.