使用 Sinatra 创建仅接受特定内容类型的路由

发布于 2024-12-17 05:11:18 字数 554 浏览 2 评论 0原文

我正在尝试使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

许久 2024-12-24 05:11:18

请求不包含“Content-Type”标头,而是包含“Accept”。 Sinatra 基本上应该只响应包含“application/json”的“Accept”请求。只是为了确保:

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

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
笑脸一如从前 2024-12-24 05:11:18

阅读此

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 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.

恬淡成诗 2024-12-24 05:11:18

我认为它是这样的:

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

i would think it is something like:

pass unless request.accept? == 'application/json'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文