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?

Answers


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.


Another way to force devise to trigger a 401 response is to add Accept: application/json in the request headers on the client side.


Need Your Help

Is D3DImage causing airspace problem?

wpf interop managed-directx

A DirectX scene can be drawn inside of a WindowsFormsHost, but this solution concerns struggling with some interop issues, mainly the 'airspace' problem. Thus, before creating whole framework for t...

Have C++11 some portable and effective way to access enclosing class from nested class?

c++ c++11 nested-class offsetof outer-classes

What I am needing can be done by storing this pointer of enclosing class into nested class for example this way: