使用Sinatra创建路线以仅接受特定的Content-type [英] Creating a route with Sinatra to only accept a certain Content-type

查看:142
本文介绍了使用Sinatra创建路线以仅接受特定的Content-type的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Sinatra创建一条仅接受Content-type: application/json的POST而没有成功的路由.

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

我的方法如下:

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

使用curl进行测试,我已经看到:provides => :json将路由配置为使用Content-Type: application/json进行响应.

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

是正确的,因为我还希望以JSON消息响应POST请求,但我真的需要此路由仅以Content-Type: application/json响应POST请求,而不响应其他请求(例如,其他响应(例如Content-Type: application/xml))

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

Sinatra中是否有任何方法可以将路由限制为仅接受具有特定Content-Type的请求?

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

推荐答案

请求不包含"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:

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

这篇关于使用Sinatra创建路线以仅接受特定的Content-type的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆