ruby-on-rails - Ruby on Rails - 无法在某些操作中设置 cookie
问题描述
我正在尝试设置target_path
非授权用户尝试访问的 cookie,并在授权后将他重定向到目标。一切正常,但后来我尝试使用 POST/PATCH/PUT 请求设置为目标edit_test_path
或create_test_path
其他方法,似乎没有设置任何 cookie。可能是什么情况?
application.rb - 我在这里设置 cookie。authenticate_user!
调用几乎每个before_action
控制器
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
session_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
响应或。location
redirect_to
cookies[:target_path]
root_path
然后浏览器理解它应该进行重定向并将 GET 请求发送到location
标头中指定的 URL。您不能也不应该尝试告诉它执行 POST/PUT/PATCH 请求 - 这些类型的请求通常还需要与请求一起出现的某种数据(例如提交的表单)。无论如何,您在重定向到登录页面期间丢失了所有这些数据。
我想说的是 - 仅将这些重定向用于 GET 请求。它不适用于 POST/PUT/PATCH。
推荐阅读
- vue.js - axios - 无法对数组进行响应
- php - 致命错误:不能将字符串偏移量用作数组
- oracle - 在 Oracle 中将小时变量添加到日期变量
- javascript - 函数调用相互影响
- c++ - A pthread with SCHED_RR and higher real time priority failed to preempt a kthread in kernel module with lower priority
- python - I'm trying to adapt the example of a cnn-lstm for a univariate time series from a tutorial blog to an airline passenger problem written with LSTM
- rust - 什么是正确的 Rust 内联汇编格式?
- c++ - error: invalid types ‘double[unsigned int]’ for array subscript
- python - ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers'
- javascript - React.js app works fine in development mode but has errors after building (production mode)