问题描述
使用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
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。之后,一切按预期进行。