rails 4- 401未经授权的error handling
我正在制作一个简单的quora,如问题答案网站登录使用设计。 我试图使用ajax在问题索引本身中呈现表单。 一切似乎工作正常,但没有用户登录时服务器说401未经授权已完成,似乎没有任何事情发生。 控制台响应:
Started GET "/questions/new" for 127.0.0.1 at 2017-07-18 18:30:54 +0530 Processing by QuestionsController#new as JS Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
controller: def new @question = Question.new(:user=>current_user) respond_to do |format| format.js {} end end
def new @question = Question.new(:user=>current_user) respond_to do |format| format.js {} end end
我知道这是因为before_action :authenticate_user!
在问题控制器中。 网络响应中的Chrome控制台也说“您需要先登录或注册才能继续”。
此外,我尝试了byebug,但后来才知道流程从未达到新的行动。
我想知道如何处理这个错误。 要么显示我需要在页面顶部登录或注册为通知或提醒,要么重定向到登录页面。
编辑:我正在使用remote: true
用于调用ajax。 在索引页面上的新问题链接中。
这在控制器中最容易处理。 创建一个名为“check_user”的方法:
def check_user return if user_signed_in? redirect_to new_user_session_path, error: 'You must log on to view this part of the site' end
然后我们可以决定我们要为每个控制器检查用户的页面。 如果您想限制用户的每个问题页面,那么只需执行以下操作:
class QuestionsController < ApplicationController before_action :check_user ... end
这将在每个Question Controller操作之前执行该方法。 或者,如果您希望任何人能够查看说索引和显示页面而不是其他任何页面:
before_action :check_user, except: [:index, :show]
@Mark让你知道如何在控制器上实现授权,但我看到你在这里使用json
响应,所以服务器重定向可能不是一个好选择。
def new @question = Question.new(:user=>current_user) respond_to do |format| format.js { body: {}, status: authorized? ? 200 : 401 } end end
然后,根据您在客户端收到的状态,您可以轻松地进行重定向。