Ruby on Rails:如何检测JSON是否访问?

Hen*_*hiu 24 ruby-on-rails

我有一个调用控制器方法getInfo的GET URL.可以通过mydomain.com/getInfo.json?params=BLAHBLAH或mydomain.com/getInfo?params=BLAHBLAH调用它

在控制器中,有没有办法检测用户如何调用它?

Rob*_*ers 31

是.在控制器中,您可以调用该request.format方法来确定用户请求的格式.

如果您需要的不仅仅是格式,您可以查看request.url完整的URL.有关该request对象的更多详细信息,请参见此处.

  • 提示:您可以对返回的[`Mime :: Type`](http://api.rubyonrails.org/v2.3.8/classes/Mime/Type.html)进行`=='比较,例如`request.format =='json'.还有一个方便的`#html?`方法,例如`before_action:do_something if:"request.format.html?"` (9认同)

小智 16

在控制器的特定方法中,您可以响应不同的格式 - 例如:

respond_to do |format|
  format.html
  format.json { render :json => @user }
end
Run Code Online (Sandbox Code Playgroud)

您可以响应各种格式(xml,js,json等) - 您可以在此处获取有关respond_to以及如何在控制器中使用它的更多信息:

http://apidock.com/rails/ActionController/MimeResponds/InstanceMethods/respond_to

  • 为了完全讨厌这个 - 这个例子有效,但它并不是OP所要求的.此示例设置对各种类型的调用的响应,它实际上并不告诉您的应用程序此特定调用是否是JSON API请求与"HTML请求" (3认同)

kon*_*ung 11

这是一个实际有点人为的工作示例,它回答了如何检测调用是否是JSON/XML API调用与"HTML"调用的问题.(接受的答案没有回答这个问题,只是告诉你如何回应各种格式)

# We can use this in a before_filter
skip_before_action :verify_authenticity_token, if: :api_request?

# Or in the action
def show
  @user = if api_request?
            User.where(api_token: params[:token]).first
          else
            User.find(params[:id])
          end
  respond_to do |format|
    format.html 
    format.json { render :json => @user }
  end
end

private
  def api_request?
    request.format.json? || request.format.xml?
  end
Run Code Online (Sandbox Code Playgroud)

使用respond_to设置不同类型的响应,但它不会告诉您的应用程序如何进行调用,除非您添加一些额外的代码(请参阅下面的粗略示例,仅用于说明这一点.)

我不建议这样做,询问request更安全,并且有用10倍,因为下面的方法仅在请求生命周期的后期(在响应发送回客户端之前)才有用.如果您在之前的过滤器中有任何逻辑,则根本不起作用.

# Have no way of using it in a before_filter
# In your controller
def show
  # I want to know if the call was JSON API - right here 
  # This approach wouldn't help at all. 
  @user = User.find(params[:id])
  respond_to do |format|
    format.html { @api_request = false}
    format.json { @api_request = true; render :json => @user }
  end
end

def api_request?
  @api_request
end
Run Code Online (Sandbox Code Playgroud)


JGu*_*ezC 8

就像这样简单:

request.path_parameters[:format] == 'json'
Run Code Online (Sandbox Code Playgroud)


Cru*_*nez 6

检查JSON的方法列表

request.format == 'json'
request.format == :json
request.format.json?
request.path.match('json')
request.url.match('json')
respond_to do |format|
  format.json { render json: [] }
end
Run Code Online (Sandbox Code Playgroud)

您还可以检查请求是否为ajax请求

request.xhr?
Run Code Online (Sandbox Code Playgroud)