跳过JSON POST API

时间:2015-09-13 14:23:36

标签: ruby-on-rails json ajax

是否有办法跳过require_user for JSON API。

我有一个Web应用程序,它将JSON POST请求发送到我的rails应用程序并期望JSON响应。但是,每个请求都被重定向到登录页面,因为(我假设)它没有被注册为有会话。

到目前为止,这就是我所拥有的:

memo_main_tester_controller.rb

class MemoMainTesterController < ApplicationController

  before_action :require_user, unless: :json_request?
  ...

这是API方法的地方

application_controller.rb

class ApplicationController < ActionController::Base

  protect_from_forgery
  skip_before_action :verify_authenticity_token, if: :json_request?

  helper_method :current_user
  ...

  def json_request?
    request.format.symbol == :json
  end

  private
  def current_user
    User.where(id: session[:user_id]).first
  end

  def require_user
    the_user = current_user
    unless the_user
      redirect_to login_path, notice: 'You must be logged in to view that page.'
    end
  end

我通过SO搜索了json_request?方法,但我觉得它没有用。

当我向POST发送memo_main_tester_controller请求时,AJAX请求会点击302,并向我发送一个200的登录页面。如何停止此操作并获得预期的JSON响应?

1 个答案:

答案 0 :(得分:0)

你应用应该在这个阶段工作。 json_request?看起来也很好。认为rewrite it有一种更通用的方式:

def json_request?
  request.format.json?
end

我认为问题应该是您从AJAX调用中调用的请求URL不是以.json结尾。

相关问题