簡體   English   中英

如何使用 AJAX 啟動 devise 注銷

[英]How to initiate a devise logout with AJAX

我想使用 Sweetalert2 啟動 devise 注銷/注銷,但下面的代碼在 Rails 中生成無效的 CSRF 令牌錯誤。

下面的代碼向 devise 發起 DELETE HTTP 請求注銷 URL 但那是發生 CSRF 錯誤並且不會注銷的時候。 請注意 destroy_user_session_path 的 ERB 標記。 如果我硬編碼指向注銷頁面的鏈接,它會產生相同的錯誤。

任何有關如何解決此問題的幫助將不勝感激。

function logoutSwal() {
    Swal.fire({
    title: 'Ready to Leave?',
    text: "Select 'Logout' below if you are ready to end your current session.",
    type: 'question',
    showCancelButton: true,
    confirmButtonColor: '#3085d6',
    confirmButtonText: 'Logout'
    }).then((result) => {
        if (result.value) {
            fetch('<%= destroy_user_session_path %>', {
                method: 'DELETE'
            }
        }
    })
}

更新

下面的 function 現在部分工作,它正確注銷(刪除會話)但不重定向到登錄頁面。 如果我刷新頁面 (CTRL-R),我會被帶到登錄頁面。 我懷疑這個問題現在與 devise controller 和響應 AJAX / Z0ECD11C1D7A287A402F8?

我是否必須更新 controller 才能響應(即重定向)此請求?

Function:

window.ajaxLogout = function(logoutUrl) {
    Swal.fire({
        title: 'Ready to Leave?',
        text: "Select 'Logout' below if you are ready to end your current session.",
        type: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        confirmButtonText: 'Logout'
    }).then((result) => {
        if (result.value) {
            $.ajax({
                url: logoutUrl,
                headers: {
                    'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
                },
                type: "DELETE"
            })
        }
    })
}

運行 function 時的日志條目:

Started DELETE "/logout" for IPXXX at 2019-10-29 19:14:47 -0400

Processing by Users::SessionsController#destroy as */*
  User Load (0.7ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Account Load (0.3ms)  SELECT  "public"."accounts".* FROM "public"."accounts" WHERE "public"."accounts"."subdomain_name" = $1 LIMIT $2  [["subdomain_name", "demo"], ["LIMIT", 1]]
   (0.2ms)  BEGIN
   (0.6ms)  SELECT COUNT(*) FROM "users"
   (0.3ms)  COMMIT
Completed 204 No Content in 19ms (ActiveRecord: 3.8ms)

最后我只是使用了 ajax 成功 function 重定向到登錄頁面。

window.ajaxLogout = function(logoutUrl, loginUrl) {
  Swal.fire({
    title: "Ready to Leave?",
    text: "Select 'Logout' below if you are ready to end your current session.",
    icon: "question",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    confirmButtonText: "Logout"
  }).then(result => {
    if (result.value) {
      $.ajax({
        url: logoutUrl,
        type: "DELETE",
        success: function() {
          window.location.href = loginUrl;
        }
      });
    }
  });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM