Creating a route with Sinatra to only accept a certain Content-type

我的梦境 提交于 2019-12-22 04:37:21

问题


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'


来源:https://stackoverflow.com/questions/8225689/creating-a-route-with-sinatra-to-only-accept-a-certain-content-type

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