You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ruby API实现用户登出时出现500内部服务器错误求助

问题分析

你遇到的500内部服务器错误,根源是Devise内置的verify_signed_out_user回调会调用respond_to_on_destroy方法,而这个方法依赖控制器的respond_to设置——你注释掉respond_to :json后,控制器失去了该方法,从而触发NoMethodError。

解决方案

方案1:恢复respond_to :json配置

在会话控制器顶部添加respond_to :json,满足Devise父控制器方法对响应格式的依赖:

class Users::SessionsController < Devise::SessionsController
  respond_to :json # 必须添加这一行

  def create
    email = params[:email]  
    password = params[:password]

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

    if user&.valid_password?(params[:password])  
      sign_in(user)  
      render json: { message: "Logged in successfully", user: user.as_json(only: [:id, :email]) }, status: :ok  
    else  
      render json: { error: "Invalid email or password" }, status: :unauthorized  
    end  
  end

  def destroy  
    if current_user  
      sign_out(current_user)  
      render json: { message: "Logged out successfully" }, status: :ok  
    else  
      render json: { error: "No active session" }, status: :unauthorized  
    end  
  end  
end

方案2:跳过Devise的verify_signed_out_user回调

如果不想使用respond_to配置,可以直接跳过这个触发报错的回调:

class Users::SessionsController < Devise::SessionsController
  skip_before_action :verify_signed_out_user # 跳过默认回调

  def create
    # 保持原create方法代码不变
    email = params[:email]  
    password = params[:password]

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

    if user&.valid_password?(params[:password])  
      sign_in(user)  
      render json: { message: "Logged in successfully", user: user.as_json(only: [:id, :email]) }, status: :ok  
    else  
      render json: { error: "Invalid email or password" }, status: :unauthorized  
    end  
  end

  def destroy  
    if current_user  
      sign_out(current_user)  
      render json: { message: "Logged out successfully" }, status: :ok  
    else  
      render json: { error: "No active session" }, status: :unauthorized  
    end  
  end  
end
额外注意事项
  • 测试登出请求时,确保Thunderclient携带了登录时获取的会话Cookie(会话式认证依赖Cookie识别当前用户),否则current_user会返回nil,触发"无活跃会话"的错误。
  • 你的Devise版本为4.9.4,该版本的verify_signed_out_user回调确实会调用respond_to_on_destroy,以上两种方案均可解决问题。

内容的提问来源于stack exchange,提问作者user26563909

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 03:33:13