首页 > 解决方案 > Heroku Rails API 通过 Post fetch 请求给出 500 Internal Server Error

问题描述

我正在尝试向上传到 Heroku 的 Rails API 发出 POST 请求。目前我正在使用邮递员进行测试,以确保它在继续在heroku应用程序之间进行测试之前在那里工作。在本地,我可以与我的 React 前端和 Rails API 后端进行交互。本地主机没有问题。

URL: https://appname.herokuapp.com/api/v1/users/

headers: 
key: Access-Control-Allow-Origin, value: *
//I have also removed the access control allow origin so with and without.
key: Content-type, value: application/json

为创建用户而传入的数据确实已创建,但返回响应为 500 internal server error

[
{
"id": 1,
"first_name": "Roger",
"last_name": "Perez",
"email": "roger@yahoo.com",
"birthday": "2000-10-10",
"gender": "male",
"avatar": null,
"home_base": null,
"initials": null,
"comments": [],
"events": [],
"user_events": [],
"messages": []
},

导轨

class Api::V1::UsersController < ApplicationController
  # before_action :requires_login, only: [:index]
  # before_action :requires_user_match, only: [:show]

  def index
    @users = User.all
    render json: @users
  end

  def create
    puts "#{params}"
    @user = User.new(get_params)
    @verify_user = User.find_by(email: params[:email])
    @user.email = params[:email]
    @user.password = params[:password]
    # if (@user.save)
    if (@verify_user === nil && @user.save )
      token = generate_token
      render json: {
        message: "You have been registed",
        token: token,
        id: @user.id,
        status: :accepted
        }
    elsif (@verify_user.valid?)
      render json: {
        message: "You already have an account",
         errors: @user.errors.full_messages,
         verify: @verify_user,
         status: :conflict}
    else
      render json: {
         errors: @user.errors.full_messages,
         status: :unprocessable_entity
       }

    end

  end

private

  def get_params
    params.permit(:first_name, :last_name, :email, :password, :birthday, :gender,)
  end
end 

宝石文件

source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.3.3'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 5.2.0'
# Use postgresql as the database for Active Record
gem 'pg', '>= 0.18', '< 2.0'
# Use Puma as the app server
gem 'puma', '~> 3.11'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
# gem 'jbuilder', '~> 2.5'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use ActiveModel has_secure_password

# Use ActiveStorage variant
# gem 'mini_magick', '~> 4.8'

# Use Capistrano for deployment
# gem 'capistrano-rails', group: :development
gem "rails_12factor", group: :production
gem 'jwt'
gem 'bcrypt', '~> 3.1.7'
gem 'rest-client', '~> 2.0', '>= 2.0.2'
# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.1.0', require: false
gem 'http'
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
gem 'rack-cors'
gem 'active_model_serializers', '~> 0.10.0'
gem "dotenv-rails"

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  gem 'listen', '>= 3.0.5', '< 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end


# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

日志

2018-07-20T17:56:18.618067+00:00 heroku[router]: at=info method=POST path="/sessions" host=meetfriends-api.herokuapp.com request_id=e6471540-3038-46d8-ae68-3c671266ecd8 fwd="71.190.202.18" dyno=web.1 connect=0ms service=98ms status=500 bytes=203 protocol=https

cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

如果我遗漏任何细节,请告诉我。谢谢你的帮助。

标签: ruby-on-railsherokufetchhttp-status-code-500

解决方案


由于这是我第一次将应用程序上传到 Heroku,我忽略了一个简单的错误。我需要为应用程序设置环境变量,因为我使用的是 JWT Auth 并且在我的 .env 文件中有没有上传到我的 github 的密钥。

https://devcenter.heroku.com/articles/config-vars

配置环境变量后,我不再收到 500 内部服务器错误。


推荐阅读