SystemStackError堆栈级别太深-呈现JSON

问题描述

使用Rails API构建。提交API登录请求时收到错误SystemStackerror (stack level too deep)

错误在于在此行render json: {user: @user,token: token}.as_json,serializer: nil,:status => :ok上呈现JSON

尝试过的解决方案:

SystemStackError (stack level too deep)

Ruby 2.4 and Rails 4 stack level too deep (SystemStackError)

https://github.com/rmosolgo/graphql-ruby/issues/2214

用户控制器:

class UsersController < ApplicationController
  #auth_login only action to be authorized before an action
  before_action :authenticate_request,only: [:auto_login,:edit]

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

    if @user && @user.authenticate(params[:password])
      token = encode_token({email: @user.email})
      render json: {user: @user,:status => :ok
    else
      render json: {error: "Invalid email or password"},:status => :unauthorized
    end
  end

  private

  def default_serializer_options
    {
    serializer: nil
    }
  end
end

由于不一致,该错误令人讨厌!有时它没有问题,有时却没有问题。不确定该在哪里使用,因为我看不到递归的代码

更新:带有encode_token

的Application Controller
class ApplicationController < ActionController::API
    before_action :authenticate_request

    def encode_token(payload)
        JWT.encode(payload,'s3cr3t')
    end

    def auth_header
        #requesting the header type of authorization (with token) that we will declare through our api requests
        # { Authorization: 'Bearer <token>' }
        request.headers['Authorization']
    end

    def decoded_token
        if auth_header
            #going to take the token and decode it
            token = auth_header.split(' ')[1]
            # header: { 'Authorization': 'Bearer <token>' }
            begin
                puts token
                JWT.decode(token,'s3cr3t') #The header is sending the correct token but returning a fail.
            rescue JWT::DecodeError
                # puts "fail"
                nil
            end
        end
    end

    def logged_in_user
        #consults decode_token to check the header for valid information
        if decoded_token
            puts "Do"
            email = decoded_token[0]['email']
            @user = User.find_by(email: email)
        end
    end

    def logged_in?
        #returns true or false
        !!logged_in_user
    end

    def authenticate_request
        #consults logged_in? see see if user is authorized
        render json: { message: 'Please log in' },status: :unauthorized unless logged_in?
    end
end

解决方法

对于该解决方案,我发现呈现@user时存在问题。尽管我已经通过rake db:reset等重置了数据库,但是我需要重置postgres。之后,一切按预期进行。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...