Arun Arun - 21 days ago 5
Ajax Question

How to prevent Devise from issuing a 302 redirect using AJAX

I am creating an Angular app that signs up and logs in users via AJAX using a Rails backend with Devise. Everything works great and users get added to the database, but I get a 302 response which is triggering the AJAX error callback.

I've tried adding the following to registrations_controller.rb with no luck:

class RegistrationsController < Devise::RegistrationsController
respond_to :json

private

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

def account_update_params
params.require(:user).permit(:firstname, :lastname, :email, :password, :password_confirmation, :current_password, :username)
end

end


And of course making sure to use this controller in the routes:

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

resources :messages
end


What is the best way to trigger a 200 or 201 response from Devise?

Answer

So it turns out that Devise by default is set up to use its views to handle the signup/login process. That being said, if you use AJAX to make the request, you will always get a 302 redirect because Devise is sending you over to the next HTML view.

To stop this from happening with AJAX it is important to use the .json extension to the Devise endpoints. For example, to create a user:

POST /users.json

Or to sign in a user:

POST /users/sign_in.json

This is because Devise uses respond_to in its logic, which requires this extension.

Comments