Ruby 在 Rails - 无法在某些操作中设置 cookie

Ruby on Rails - Can't set cookies in some actions

我正在尝试在 cookies target_path 中设置非授权用户试图访问并在授权后将他重定向到目标。一切正常,但后来我尝试将 edit_test_pathcreate_test_path 和其他方法设置为 POST/PATCH/PUT 请求,但似乎没有设置任何 cookie。会是什么情况?

application.rb - 我在这里设置 cookie。 authenticate_user! 调用几乎每个控制器 before_actions

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session

  helper_method :current_user,
                :logged_in?

  private

  def authenticate_user!
    unless current_user
      cookies[:target_path] = request.path_info

      redirect_to login_path, alert: 'Verify Email or Password'
    end
  end

  def current_user
    @current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
  end

  def logged_in?
    current_user.present?
  end
end

sessions_controller.rb - 我正在尝试从此处的 cookie 重定向到目标

class SessionsController < ApplicationController
  def new; end

  def create
    user = User.find_by(email: params[:email])

    if user&.authenticate(params[:password])
      session[:user_id] = user.id

      cookies[:target_path] ? (redirect_to cookies[:target_path]) : (redirect_to root_path) # With verb POST cookies don't work
    else
      flash.now[:alert] = 'Verify Email or Password'
      render :new
    end
  end

  def exit
    session[:user_id] = nil

    redirect_to login_path
  end
end

我不认为,您可以通过 POST/PUT/PATCH 请求来做到这一点。当您执行 redirect_to 时,rails 发送 302 Found 响应,在 redirect_to 的参数中指定 location 在您的情况下 cookies[:target_path]root_path.

浏览器然后理解它应该进行重定向并将 GET 请求发送到 locationheader 中指定的 URL。您不能也不应该尝试告诉它执行 POST/PUT/PATCH 请求 - 这些类型的请求通常还需要与请求一起提供的某种数据(例如提交的表单)。无论如何,您在重定向到登录页面期间丢失了所有这些数据。

我想说的是 - 仅对 GET 请求使用这些重定向。它不适用于 POST/PUT/PATCH.