我在Rails 7上持久化会话有问题。我甚至没有在任何地方重定向,只是停留在一个页面上。
application_controller.rb
class ApplicationController < ActionController::API
include ActionController::Cookies
end
application.rb
require_relative "boot"
require "rails/all"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CsmBack
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 7.0
# Configuration for the application, engines, and railties goes here.
#
# These settings can be overridden in specific environments using the files
# in config/environments, which are processed later.
#
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
# Must add these lines!
# Adding back cookies and session middleware
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore, key: '_namespace_key'
# Use SameSite=Strict for all cookies to help protect against CSRF
config.action_dispatch.cookies_same_site_protection = :strict
end
end
sessions_controller.rb
def login
if session[:user_id]
return render json: {errors: "Username or Password Wrong"}
end
user=User.find_by(username: params[:username])
if user&.authenticate(params[:password])
session[:user_id] = user.id
render json: user
else
render json: {errors: "Username or Password Wrong"}
end
end
如果最后一个工作,我应该能够点击按钮触发它在一行两次,并得到不同的值,但我甚至没有得到。
如果客户端尝试登录而不先注销,您似乎会向客户端抛出错误。根据我在这里看到的,您的服务器端代码(不管看起来有多糟糕)是没问题的。你可能想看看你的客户端,也许设置一个代理