使用 Sinatra 创建仅接受特定内容类型的路由
我正在尝试使用 Sinatra 创建一条仅接受带有 Content-type: application/json
的 POST 的路由,但没有成功。
我的方法如下:
post '/dogs', :provides => :json do
# returns here a json response
end
用curl测试,我看到:provides =>; :json
配置路由以使用 Content-Type: application/json
进行响应。
没错,因为我还想用 JSON 消息响应 POST 请求,但我确实需要该路由仅响应带有 Content-Type: application/json
的 POST 请求,而不是,例如,给其他人(例如Content-Type:application/xml
)。
Sinatra 有什么方法可以限制路由只接受特定 Content-Type
的请求吗?
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
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请求不包含“Content-Type”标头,而是包含“Accept”。 Sinatra 基本上应该只响应包含“application/json”的“Accept”请求。只是为了确保:
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:
阅读此
http://rack.rubyforge.org/doc/classes/Rack/Request.html
request.content_type
会告诉您Phil 对于 RFC 的看法可能是正确的,但实际上很多事情都会在 POST 请求中放入内容类型,因此了解它是什么很有用。
Read this
http://rack.rubyforge.org/doc/classes/Rack/Request.html
request.content_type
will tell youPhil 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.
我认为它是这样的:
i would think it is something like: