简体   繁体   English

在 heroku 上部署时,rails-react 应用程序上的身份验证方法遇到内部服务器错误 (500) 和类型错误

[英]Running into Internal Server Error (500) and typeerror for authentication method on rails-react app when deployed on heroku

I am getting a 500 error for my authentication method (trying to log in).我的身份验证方法出现 500 错误(尝试登录)。 I've been trying things for these few days, and getting frustrated so I'm reaching out for help!这几天我一直在尝试,但感到沮丧,所以我正在寻求帮助! It is odd because it is working perfectly when I do it locally, but only doesn't work when I try to do it on a deployed app.这很奇怪,因为当我在本地执行它时它工作得很好,但只有当我尝试在已部署的应用程序上执行它时才不起作用。 I'm using a react - rails on ruby app.我正在使用 react-rails on ruby​​ 应用程序。

On the console, it shows:在控制台上,它显示:

POST https://bookend-app-api.herokuapp.com/users/login 500 (Internal Server Error)
(anonymous) @ Home.jsx:40
Home.jsx:52 error SyntaxError: Unexpected end of JSON input
at Home.jsx:41

And here is my heroku log:这是我的heroku日志:

2020-10-21T08:09:08.910811+00:00 app[web.1]: * Version 4.3.5 (ruby 2.6.3-p62), codename: Mysterious Traveller
2020-10-21T08:09:08.910813+00:00 app[web.1]: * Min threads: 5, max threads: 5
2020-10-21T08:09:08.910813+00:00 app[web.1]: * Environment: production
2020-10-21T08:09:08.911143+00:00 app[web.1]: * Listening on tcp://0.0.0.0:9349
2020-10-21T08:09:08.911592+00:00 app[web.1]: Use Ctrl-C to stop
2020-10-21T08:09:09.393243+00:00 heroku[web.1]: State changed from starting to up
2020-10-21T08:09:10.436899+00:00 app[web.1]: I, [2020-10-21T08:09:10.436789 #4]  INFO -- : [e98560d0-f62c-4654-ab05-7b648397778e] Started POST "/users/login" for 39.123.239.97 at 2020-10-21 08:09:10 +0000
2020-10-21T08:09:10.444498+00:00 app[web.1]: I, [2020-10-21T08:09:10.444415 #4]  INFO -- : [e98560d0-f62c-4654-ab05-7b648397778e] Processing by UsersController#login as */*
2020-10-21T08:09:10.444554+00:00 app[web.1]: I, [2020-10-21T08:09:10.444507 #4]  INFO -- : [e98560d0-f62c-4654-ab05-7b648397778e]   Parameters: {"user"=>{"username"=>"katy", "password"=>"[FILTERED]"}}
2020-10-21T08:09:10.516954+00:00 app[web.1]: D, [2020-10-21T08:09:10.516828 #4] DEBUG -- : [e98560d0-f62c-4654-ab05-7b648397778e]   User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."username" = $1 LIMIT $2  [["username", "katy"], ["LIMIT", 1]]
2020-10-21T08:09:10.844349+00:00 heroku[router]: at=info method=POST path="/users/login" host=bookend-app-api.herokuapp.com request_id=e98560d0-f62c-4654-ab05-7b648397778e fwd="39.123.239.97" dyno=web.1 connect=0ms service=407ms status=500 bytes=374 protocol=https
2020-10-21T08:09:10.840623+00:00 app[web.1]: I, [2020-10-21T08:09:10.840511 #4]  INFO -- : [e98560d0-f62c-4654-ab05-7b648397778e] Completed 500 Internal Server Error in 396ms (ActiveRecord: 30.4ms | Allocations: 8446)
2020-10-21T08:09:10.841215+00:00 app[web.1]: F, [2020-10-21T08:09:10.841144 #4] FATAL -- : [e98560d0-f62c-4654-ab05-7b648397778e]
2020-10-21T08:09:10.841216+00:00 app[web.1]: [e98560d0-f62c-4654-ab05-7b648397778e] TypeError (no implicit conversion of nil into String):
2020-10-21T08:09:10.841217+00:00 app[web.1]: [e98560d0-f62c-4654-ab05-7b648397778e]

My application-controller:我的应用程序控制器:

class ApplicationController < ActionController::API

    def authenticate_token
        # puts "AUTHENTICATE JWT"
        render json: { status: 401, message: 'Unauthorized' } unless decode_token(bearer_token)
    end
  
    def bearer_token
        # puts "BEARER TOKEN"
        header = request.env["HTTP_AUTHORIZATION"]

        pattern = /^Bearer /
        # puts "TOKEN WITHOUT BEARER"
        header.gsub(pattern, '') if header && header.match(pattern)
    end
  
    def decode_token(token_input)
        # puts "DECODE TOKEN, token input: #{token_input}"
        # token =
        JWT.decode(token_input, ENV['JWT_SECRET'], true)
        # render json: { decoded: token }
    rescue
        render json: { status: 401, message: 'Unauthorized' }                          
    end

    def get_current_user 
        return if !bearer_token   
        decoded_jwt = decode_token(bearer_token) 
        User.find(decoded_jwt[0]["user"]["id"])
    end 

    def authorize_user
        render json: { status: 401, message: "Unauthorized" } unless get_current_user.id == params[:id].to_i       
    end

    # delete if error occurs
    def session_user
        decoded_hash = decoded_token
        if !decoded_hash.empty?
            user_id = decoded_hash[0]['user_id']
            @user = User.find_by(id: user_id)
        else
            nil
        end
    end
    # 
  
  end

application.rb:应用程序.rb:

require_relative 'boot'

require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "active_record/railtie"
require "active_storage/engine"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_mailbox/engine"
require "action_text/engine"
require "action_view/railtie"
require "action_cable/engine"
# require "sprockets/railtie"
require "rails/test_unit/railtie"

# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)

module BookwormAppApi
  class Application < Rails::Application
    # Initialize configuration defaults for originally generated Rails version.
    config.load_defaults 6.0

    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration can go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded after loading
    # the framework and any gems in your application.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
  end
end

Also, this is the block of code in Home.jsx describing the POST method used to log in and where it's giving a typeerror.此外,这是 Home.jsx 中的代码块,描述用于登录的 POST 方法以及它在哪里给出类型错误。 (this typeerror doesn't occur locally.) (此类型错误不会在本地发生。)

useEffect(()=>{
        if(loginInfo.username !== undefined){
        let requestOptions = {
        method: 'POST',
        body: LoginFormdata,
        redirect: 'follow'
        };
        
        fetch(`${apiUrl}/users/login`, requestOptions)
        .then(response => response.json())
        .then(result => {
            console.log('FETCH (post) (login) from home', result)
            if (result.status==200){
                authorization(result.token, result.user.id)
                handleAuthenInfoFromApp(result.token, result.user.id)
            }
            else{
                setLoginSuccessful(false)
            }
        })
        .catch(error => console.log('error', error));
        }
    }, [loginInfo])

Any help would be appreciated!任何帮助,将不胜感激!

I'm unfamiliar with ruby, but from what I can make up out of the error and the react part is that there are no authorisation headers added to the fetch method options.我不熟悉 ruby​​,但从我可以弥补的错误和反应部分来看,没有向 fetch 方法选项添加授权标头。 I'd suggest doing the following:我建议执行以下操作:

1: Use postman to verify your request. 1:使用邮递员验证您的请求。 Set all the headers, body, authorisation.设置所有标题、正文、授权。 Postman helps you a little bit with authorisation headers, they can be confusing. Postman 可以帮助您处理授权标头,它们可能会令人困惑。

2: Look at the postman headers and make sure all of them are the same in the fetch headers in js. 2:查看 postman 头文件,确保它们在 js 中的 fetch 头文件中都是相同的。

3: Add headers in the way that is described by mdn docs 3:按照mdn docs描述的方式添加headers

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Heroku 上部署的 Rails API 在开发过程中引发内部服务器错误 (500) - Deployed Rails API on Heroku throws internal server error (500) while it works on development Heroku Rails-500内部服务器错误 - Heroku Rails - 500 Internal Server Error Rails/React App Signup 抛出 500 内部服务器错误 - Rails/React App Signup throwing 500 internal server error Heroku 500内部服务器错误,TypeError(没有将Symbol隐式转换为Integer): - Heroku 500 internal server error, TypeError (no implicit conversion of Symbol into Integer): Ruby on Rails应用程序500 Internal Server错误 - Ruby on Rails app 500 Internal Server error 在Heroku中使用Webpack部署Rails应用程序时出错 - Error when deployed the rails app with webpack in the Heroku 关于Heroku状态500内部服务器错误的Rails应用程序(很抱歉,出现了问题) - Rails app on Heroku status 500 internal server error (We're sorry but something went wrong) axios / rack-cors / react-rails / heroku:注销时出现内部服务器错误500,刷新时没有持久性 - axios/rack-cors/react-rails/heroku: Internal Server Error 500 on sign out, no persistence on refresh Heroku 500内部服务器错误 - Heroku 500 Internal Server Error Heroku 500内部服务器错误nil:NilClass的未定义方法&#39;username&#39; - Heroku 500 internal server error undefined method 'username' for nil:NilClass
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM