Tazoh Yanick
Tazoh Yanick

Reputation: 23

Rails API path in browser gives this error NoMethodError undefined method `[]' for nil:NilClass

I have created a Rails API and when I run either this path http://localhost:3000/api/v1/records or http://localhost:3000/api/v1/items in the browser address bar, I get the error as displayed in the image below enter image description here

Below is the entire code in the application_controller.rb file

class ApplicationController < ActionController::API
  SECRET_KEY = Rails.application.credentials.jwt[:secret].to_s
  EXPIRES_IN = Rails.application.credentials.jwt[:expires_in]

  def authorized
    render json: {message: 'Please log in'}, status: 401 unless logged_in?
  end

  def encode_token(payload)
    payload[:exp] = EXPIRES_IN.days.from_now.to_i
    JWT.encode(payload, SECRET_KEY, 'HS256')
  end

  def auth_header
    return unless request.headers['Authorization']
    request.headers['Authorization'].split(' ')[1]
  end

  def decoded_token
    return unless auth_header

    token = auth_header
    begin
      JWT.decode(token, SECRET_KEY, true, algorithm: 'HS256')
    rescue JWT::DecodeError
      nil
    end
  end

  def logged_in_user
    return unless decoded_token

    user_id = decoded_token[0]['user_id']
    @current_user = User.find_by(id: user_id)
  end

  def logged_in?
    logged_in_user ? true : false
  end
end

Any help on how I can fix this will be greatly appreciated. This is the first Rails API I am building. Thanks

Upvotes: 0

Views: 1190

Answers (1)

spickermann
spickermann

Reputation: 106802

The error message is actually very precise. It tells you that there is no method [] defined on nil and it tells you where ther error is happening: in the second line of the ApplicationController.

The second line of that controller looks like this:

SECRET_KEY = Rails.application.credentials.jwt[:secret].to_s

That means if Rails compains about calling [] on a nil value then

Rails.application.credentials.jwt

must return nil.

It looks like you haven't setup the secret credentials correctly or the format of the file is somehow broken.

I suggest reading about Custom Credentials in the Rails Guides.

Upvotes: 1

Related Questions