为Sinatra设置默认content_type

时间:2011-01-08 03:07:24

标签: ruby json sinatra content-type

在Sinatra中,是否可以使content_type 'application/json'成为默认值?因为我正在写一个api。

2 个答案:

答案 0 :(得分:74)

当然,将content_type添加到before回调:

class MyApp < Sinatra::Base

  before do
    content_type 'application/json'
  end

  ...

end

Sinatra 1.1在过滤器之前引入了模式匹配:

before '/admin/*' do
  check_logged_in
end

答案 1 :(得分:2)

对于 JSON API,为所有响应设置默认 Content-Type 的最推荐方法是在 Sinatra 类中添加以下内容:

set :default_content_type, 'application/json'

它将在您的所有回复中包含一个 Content-Type: application/json 标头。