【问题标题】:Set default content_type for Sinatra为 Sinatra 设置默认 content_type
【发布时间】:2011-06-05 15:37:10
【问题描述】:

在 Sinatra 中是否可以将 content_type 'application/json' 设为默认值?因为我正在构建一个 REST API。

【问题讨论】:

    标签: json ruby rest sinatra content-type


    【解决方案1】:

    当然,将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
    

    【讨论】:

    • 谢谢!如何创建一个上下文,以便 before 过滤器仅应用于特定的一组路由而不是全部?
    • @MattDiPasquale 这应该可以解决问题:blog.alastairdawson.com/2010/07/27/a-sinatra-before-only-filter
    • @MattDePasqaule 您还可以覆盖单个路由中的内容类型。
    • sinatra 1.1 支持pattern before filter,所以不需要打补丁。
    • @Konstantin 感谢您的提醒,比我的建议要好得多。
    【解决方案2】:

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

    set :default_content_type, :json
    

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

    【讨论】:

    • 甚至set :default_content_type, :json
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-25
    • 2018-02-12
    • 1970-01-01
    • 2018-06-03
    • 2017-04-09
    • 2015-10-02
    • 1970-01-01
    相关资源
    最近更新 更多