简体   繁体   中英

Uninitialized constant error after uploading on Heroku

There is the following problem: I'm developing some Rails application on my local machine, and all is good, app works, but after uploading on Heroku there would be the following error (I saw it using 'heroku logs'):

NameError (uninitialized constant Api::V1::ApiV1Controller::UndefinedTokenTypeError)

My code:

  def require_token
    begin
      Some code which generates UndefinedTokenTypeError
    rescue UndefinedTokenTypeError => e
      render json: e.to_json
    end
  end

UndefinedTokenTypeError is in lib/errors.rb file:

  class EmptyCookieParamsError < StandardError
    def to_json
      { result_code: 1 }
    end
  end

  class UndefinedTokenTypeError < StandardError
    def to_json
      { result_code: 2 }
    end
  end

I've got the same version for Rails/Ruby on my local machine (2.0). How can I fix it? Thanks.

Running on Heroku will be using the production environment. Check to see what is different between environments/development.rb and environments/production.rb

You can try running your app in production mode on your local machine, rails server -e production

I am guessing your config.autoload_paths isn't set correctly. Should be in config/application.rb

From what I can see, you may be experiencing either a CORS -related issue or you're not authenticating properly


Cross Origin Resource Sharing

CORS is a standard HTML protocol , which basically governs which websites can "ping" your site. Facebook & Twitter's third-party widgets only work because they allow any site to send them data

For Rails to work with CORS, it's recommended to install the Rack-CORS gem . This will allow you to put this code in your config/application.rb file:

#CORS
config.middleware.use Rack::Cors do
  allow do
     origins '*'
     resource '/data*', :headers => :any, :methods => :post
  end
end

Because you're experiencing these issues on Heroku, it could be the problem you're experiencing. Even if it isn't, it's definitely useful to appreciate how CORS works


Authentication

Unless your API is public, you'll likely be authenticating the requests

The way we do this is with the authenticate_or_request_with_http_token function, which can be seen here:

  #Check Token
    def restrict_access
        authenticate_or_request_with_http_token do |token, options|
             user = User.exists?(public_key: token)
             @token = token if user
        end
    end

We learnt how to do this with this Railscast , which discusses how to protect an API. The reason I asked about your code was because the above works for us on Heroku, and you could gain something from it!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM