【问题标题】:Respond with json format to all formats requests以json格式响应所有格式请求
【发布时间】:2016-06-09 01:23:57
【问题描述】:

我在 Ruby on Rails 上实现了一个 Rest API。所以我想以 json 格式响应所有请求。我做了这个:

include ActionController::MimeResponds


before_filter :force_json

def force_json
  response.format = "json"
  #also tried
  # response.content_type = Mime[:json]
end

这两种方法都行不通。它给了我一个带有错误的 html 页面。 还有一种方法可以为整个 api 而不是每个类实现这个吗? 谢谢!

【问题讨论】:

标签: ruby-on-rails ruby json


【解决方案1】:

如果您希望它在应用程序范围内发生,您可以在应用程序控制器中执行类似的操作。

class ApplicationController < ActionController::Base
  before_action :force_json

  def force_json
     request.format = :json
  end
end

【讨论】:

    【解决方案2】:

    如果您使用 responders gem,您可以在类的顶部定义它:

    class PostsController < ApplicationController
      respond_to :json
      ...
    

    那么这个控制器会默认使用 JSON 响应。

    【讨论】:

    • 即使使用此 gem 并添加该代码,如果我请求 Content-Type text/html,我也会得到一个 html 站点。我想得到一个错误 json
    猜你喜欢
    • 2013-10-13
    • 1970-01-01
    • 1970-01-01
    • 2015-03-22
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多