sourcecode

AJAX에서 device의 401 상태를 우아하게 처리하려면 어떻게 해야 합니까?

codebag 2023. 8. 26. 11:22
반응형

AJAX에서 device의 401 상태를 우아하게 처리하려면 어떻게 해야 합니까?

용도를 궁리하여.before_filter :authenticate_user!인증된 사용자에게만 액세스를 제한합니다.

인증되지 않은 사용자가 제한된 페이지를 방문하려고 하면 자동으로 로그인 페이지로 리디렉션됩니다.

따라서 http://localhost:3000/users/edit를 열려고 하면 http://localhost:3000/users/sign_in으로 리디렉션됩니다.

이제 링크를 http://localhost:3000/users/edit로 정의하면:remote => truedevice는 JS를 통해서만 401 상태 코드를 발행합니다.

이러한 상황에 우아하게 대처하고 로그인 대화상자를 오버레이표시하거나 비원격 변형처럼 리디렉션할 수 있는 방법은 무엇입니까?

제가 단순히 활성화해야 하는 상황에 대한 기본 전략을 고안이 제공합니까?

$(document).ajaxError(function (e, xhr, settings) {
        if (xhr.status == 401) {
           $('.selector').html(xhr.responseText);
        }
    });

이것이 제가 선택한 솔루션입니다(CoffeeScript 구문).

$ ->
  $("a").bind "ajax:error", (event, jqXHR, ajaxSettings, thrownError) ->
    if jqXHR.status == 401 # thrownError is 'Unauthorized'
      window.location.replace('/users/sign_in')

그러나 이 페이지는 사용자가 처음에 방문하기를 원하는 페이지를 잊어버리기 때문에 사용성이 제한됩니다.

보다 우아한 핸들링을 위해서는 추가적인 (컨트롤러) 로직이 필요합니다.

업데이트: 올바른 리디렉션

함수 내에서,this사용자가 이동하려는 초기 URL을 보유합니다.

전화로window.location.replace(this)(로그인 페이지로 명시적으로 리디렉션하는 대신), 앱은 사용자를 처음에 의도한 대상으로 리디렉션하려고 시도합니다.

여전히 불가능하지만(무허가), 이제는 (JS/AJAX 대신) GET 통화가 될 것입니다.따라서 Devect는 사용자를 시작하고 로그인 페이지로 리디렉션할 수 있습니다.

이후 Dejece는 정상적으로 작동하여 로그인이 성공한 후 사용자를 원래 의도된 URL로 전달합니다.

버전 혼합 이벤트 바인딩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
      }
    });
});

Device 3.1.1을 사용하여 테스트한 결과, 올바르게 설정됩니다.session["user_return_to"]사용자가 다시 로그인한 후 페이지로 돌아갑니다().

추가했습니다.alert여기서 논의된 부적절한 메시지 문제를 해결하기 위한 간단한 방법으로: Dece를 사용한 RoR의 세션 시간 초과 메시지

여기 커피스크립트에 있는 제 카피 과거 행복(tm) 솔루션이 있습니다.모든 401을 로그인 페이지로 리디렉션합니다.

<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>

$(document).ajaxError (_, xhr)->
  window.location = '<%= new_user_session_path %>' if xhr.status == 401

그리고 Javascript:

<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>

$(document).ajaxError( function(event, xhr){
  if (xhr.status == 401) {
    window.location = '<%= new_user_session_path %>'
  }
});

레일즈 5.1 및 새로운 레일즈 ujs 기준으로 모든 사용자 정의 이벤트는 다음 매개 변수 하나만 반환합니다.event이 매개 변수에는 추가 속성이 있습니다.detail추가 매개 변수의 배열을 포함합니다. 변수 개 변data,status,xhr으로 .event.detail 그서아의류 401 오래것처로 합니다.ajax:error이벤트가 다음과 같습니다.

document.body.addEventListener('ajax:error', function(event) {
  var detail = event.detail;
  var response = detail[0], status = detail[1], xhr = detail[2];
  if (xhr.status == 401) {
    // handle error
  }
})

":remote = > true"를 수행하는 경우 "vmote:error" 이벤트 바인딩에서 .live를 사용할 수 있습니다.

$('#member_invite, #new_user')
        .live("ajax:success", function(evt, data, status, xhr){
          $.colorbox.close();
        })
        .live("ajax:error", function(evt, data, status, xhr){
          alert("got an error");
        });

여기서 "#new_user"는 양식 ID 값입니다.

오버레이나 대화 상자가 이미 있는 경우 메시지를 삽입하는 것이 더 우아하므로 alert() 대신 다음과 같이 하십시오.

$('.messages').html('Invalid email or password');

그리고 당신의 서명 양식에서 당신은 그냥 합니다.

<div class="messages"></div>

또는 필요한 것이 무엇이든 양식의 제목을 바꿀 수도 있습니다.

저는 그것을 할 수 있는 우아한 방법이 있는지 보고 싶습니다!

그때까지 제가 처리한 방법은 다음과 같습니다.

edit.js.erb 보기 파일에서 다음 코드를 넣을 수 있습니다.

<% case response.status
  when 200
%>
  //do what you need to do
<% when 401 %>
  //handle the 401 case, for example by redirecting to root or something
  window.location.href('/');
<% else %>
  //catch all
  alert('We\'ve had a problem, please close this, refresh the page and try again');
<% end %>

응답의 상태 코드를 확인하고 401이면 로그인 페이지로 리디렉션됩니다.

컨트롤러 레벨에서 직접 처리할 수 있는 방법이 없는지 궁금합니다.

언급URL : https://stackoverflow.com/questions/10124832/how-can-i-elegantly-handle-devises-401-status-in-ajax

반응형