Ruby on rails 跳过JSON POST API的用户和csrf身份验证
有没有一种方法可以跳过JSON API的require_用户 我有一个web应用程序,它向我的rails应用程序发送JSON POST请求,并期望得到JSON响应。但是,每个请求都被重定向到登录页面,因为我假设它没有注册为具有会话 到目前为止,这就是我所拥有的: memo\u main\u tester\u controller.rb 这就是API方法的用途 应用程序\u controller.rb 我得到了json_请求的方法?从搜索到搜索,但我认为它不起作用Ruby on rails 跳过JSON POST API的用户和csrf身份验证,ruby-on-rails,json,ajax,Ruby On Rails,Json,Ajax,有没有一种方法可以跳过JSON API的require_用户 我有一个web应用程序,它向我的rails应用程序发送JSON POST请求,并期望得到JSON响应。但是,每个请求都被重定向到登录页面,因为我假设它没有注册为具有会话 到目前为止,这就是我所拥有的: memo\u main\u tester\u controller.rb 这就是API方法的用途 应用程序\u controller.rb 我得到了json_请求的方法?从搜索到搜索,但我认为它不起作用 当我向memo\u main\u
当我向memo\u main\u tester\u控制器发送POST请求时,AJAX请求点击302,我被发送到带有200的登录页面。如何停止此操作并获得预期的JSON响应?您的应用程序应该在此阶段工作。你的请求?看起来也不错。认为有一种更通用的方法:
我认为问题应该是您在AJAX调用中调用的请求URL并没有以.json结尾。我将介绍几件事情。首先是json_请求?代码被击中了?我通常使用一个名为pry的gem进行调试。第二,您的json请求是什么样子的?你能把它加到你的问题上吗?它是.json结尾。你知道为什么require_user方法没有注册为从json登录吗?
class MemoMainTesterController < ApplicationController
before_action :require_user, unless: :json_request?
...
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
def json_request?
request.format.json?
end