How can I elegantly handle devise's 401 status in AJAX?

后端 未结 7 1977
庸人自扰
庸人自扰 2020-12-23 18:53

With devise one uses before_filter :authenticate_user! to restrict access to authenticated users only.

When an unauthenticated

7条回答
  •  Happy的楠姐
    2020-12-23 19:43

    A version mixing event binding with location.reload():

    $(function($) {
      $("#new-user")
        .bind("ajax:error", function(event, xhr, status, error) {
          if (xhr.status == 401) {  // probable Devise timeout
            alert(xhr.responseText);
            location.reload();      // reload whole page so Devise will redirect to signin
          }
        });
    });
    

    Testing with Devise 3.1.1, this does correctly set session["user_return_to"], so the user returns to the page after signing in again ().

    I added the alert as a simple way to address the inelegant message issue discussed here: Session Timeout Message in RoR using Devise

提交回复
热议问题