Devise Api: {"message":"Sign up failure. Email can't be blank and Password can't be blank"}

Viewed 131

I am having an issue with the Devise Api. I already got my web application for devise figured out, but because I want to also make an app I need to configure the API for devise which i am really struggling with. Currently the error that I am getting when im tying to sign up with curl -XPOST -H "Content-Type: application/json" -d '{ "user": { "email": "myemail2@email.com", "username": "testerr222", "password": "mypassword" } }' http://localhost:3000/api/users is "{"message":"Sign up failure. Email can't be blank and Password can't be blank"}%"

Can anybody help me with this? This seems to be a common issue but no previous solutions seem to work for me.

Here is my code:

routes.rb:

Rails.application.routes.draw do
  devise_for :users, controllers: { registrations: "users/registrations" }

  namespace :api, constraints: { format: :json } do
    devise_for :users, controllers: {
      sessions: 'api/v1/users/sessions',
      registrations: 'api/v1/users/registrations'
    }
  end
end

controllers/api/v1/registrations_controller.rb:

class Api::V1::Users::RegistrationsController < Devise::RegistrationsController
  respond_to :json
  # skip_before_action :verify_authenticity_token
  skip_forgery_protection 
  before_action :configure_sign_up_params, only: [:create]

  private
  def respond_with(resource, _opts = {})
    resource.persisted? ? register_success : register_failed
  end
  def register_success
    render json: { message: 'Signed up.' }
  end
  def register_failed
    render json: { message: "Sign up failure. #{resource.errors.full_messages.to_sentence}" }
  end
end

Thanks for your help!

1 Answers

I had the same problem and I managed to make it work as follows:

1 - In the controller you posted (Api::V1::Users::RegistrationsController) comment the line: before_action :configure_sign_up_params, only: [:create] and in private add :

def sign_up_params
    params.require(:user).permit(:username, :email, :password, :password_confirmation)
end

For a regular non-api application. Just add the following code in your ActionController . With that the extra fields are already accepted

before_action :configure_permitted_parameters, if: :devise_controller?
  respond_to :json, :html
    
    
  protected
  def configure_permitted_parameters
    devise_parameter_sanitizer.permit(:sign_up, keys: [:username])
  end

Unfortunately I couldn't get it to work with devise_parameter_sanitizer. But I hope this option helps you

Related