API Heroku Rails выдает внутреннюю ошибку сервера 500 при запросе Post fetch

Я пытаюсь сделать POST-запрос к своему Rails API, который загружен в Heroku. В настоящее время я тестирую с почтальоном, чтобы убедиться, что он там работает, прежде чем продолжить тестирование между приложениями heroku. Локально я могу взаимодействовать с моим интерфейсом React и серверной частью Rails API. Нет проблем с localhost.

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.

[
{
"id": 1,
"first_name": "Roger",
"last_name": "Perez",
"email": "[email protected]",
"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 

GEMFILE

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

Сообщите мне, если я упустил какие-либо подробности. Спасибо за любую помощь.


person Roger Perez    schedule 20.07.2018    source источник


Ответы (1)


Поскольку я впервые загружаю приложение на Heroku, я упустил простую ошибку. Мне нужно было настроить переменные среды для работы приложения, так как я использовал JWT Auth и в моем файле .env были секретные ключи, которые не загружаются на мой github.

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

После того, как я настроил переменные env, я больше не получал внутреннюю ошибку сервера 500.

person Roger Perez    schedule 26.07.2018