[英]Deployed Rails API on Heroku throws internal server error (500) while it works on development
[英]Running into Internal Server Error (500) and typeerror for authentication method on rails-react app when deployed on heroku
我的身份验证方法出现 500 错误(尝试登录)。 这几天我一直在尝试,但感到沮丧,所以我正在寻求帮助! 这很奇怪,因为当我在本地执行它时它工作得很好,但只有当我尝试在已部署的应用程序上执行它时才不起作用。 我正在使用 react-rails on ruby 应用程序。
在控制台上,它显示:
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
这是我的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]
我的应用程序控制器:
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
应用程序.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
此外,这是 Home.jsx 中的代码块,描述用于登录的 POST 方法以及它在哪里给出类型错误。 (此类型错误不会在本地发生。)
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])
任何帮助,将不胜感激!
我不熟悉 ruby,但从我可以弥补的错误和反应部分来看,没有向 fetch 方法选项添加授权标头。 我建议执行以下操作:
1:使用邮递员验证您的请求。 设置所有标题、正文、授权。 Postman 可以帮助您处理授权标头,它们可能会令人困惑。
2:查看 postman 头文件,确保它们在 js 中的 fetch 头文件中都是相同的。
3:按照mdn docs描述的方式添加headers
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.