Creating a route with Sinatra to only accept a cer

2019-04-27 04:22发布

问题:

I'm trying to create a route with Sinatra that only accepts POST with an Content-type: application/json without success.

My approach is as follows:

post '/dogs', :provides => :json do
  # returns here a json response
end

Testing with curl, I have seen that :provides => :json configures the route to respond with an Content-Type: application/json.

That's right because I want also to respond with a JSON message to the POST request but I really need that this route only respond to POST requests with a Content-Type: application/json and not, for example, to others (e.g. Content-Type: application/xml).

Is there any way in Sinatra to restrict the route to only accept requests with a certain Content-Type?

回答1:

Requests do not contain "Content-Type" header, but rather have "Accept". Sinatra should basically only respond to requests with "Accept" containing "application/json". Just to make sure:

post '/gods', :provides => :json do
  pass unless request.accept? 'application/json'
...
end


回答2:

Read this

http://rack.rubyforge.org/doc/classes/Rack/Request.html

request.content_type will tell you

Phil might be right regarding RFC but in reality many things put a content-type in a POST request, therefore it is useful to know what it is.



回答3:

i would think it is something like:

pass unless request.accept? == 'application/json'