为Sinatra设置默认content_type

ma1*_*w28 46 ruby json content-type sinatra

在Sinatra,是否可以content_type 'application/json'设置默认值?因为我正在写一个api.

Ada*_*sek 75

当然,添加content_typebefore回调:

class MyApp < Sinatra::Base

  before do
    content_type 'application/json'
  end

  ...

end
Run Code Online (Sandbox Code Playgroud)

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

before '/admin/*' do
  check_logged_in
end
Run Code Online (Sandbox Code Playgroud)


Per*_*ell 6

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

set :default_content_type, :json
Run Code Online (Sandbox Code Playgroud)

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