簡體   English   中英

SystemStackError(堆棧級別太深) - 渲染 JSON

[英]SystemStackError (stack level too deep) - rendering JSON

使用 Rails API 構建。 提交 API 登錄請求時出現錯誤SystemStackError (stack level too deep)

錯誤是圍繞在此行上render json: {user: @user, token: token}.as_json, serializer: nil, :status =>:ok

嘗試過的解決方案:

SystemStackError(堆棧級別太深)

Ruby 2.4 和 Rails 4 堆棧級別太深 (SystemStackError)

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

用戶 controller:

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, token: token}.as_json, serializer: nil, :status => :ok
    else
      render json: {error: "Invalid email or password"}, :status => :unauthorized
    end
  end

  private

  def default_serializer_options
    {
    serializer: nil
    }
  end
end

該錯誤令人討厭,因為它不一致。 有時它可以毫無問題地構建,有時則不會。 不確定 go 的位置,因為我看不到代碼遞歸的任何地方。

更新:應用程序 Controller 與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。 之后,一切都按預期工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM