我想使用Sweetalert2发起设备登出/登出,但是下面的代码在rails中生成了无效的CSRF令牌错误。
下面的代码向设备登出URL发起DELETE HTTP请求,但那是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'
}
}
})
}
UPDATE
下面的函数现在可以部分起作用,它可以正确注销(删除会话),但不会重定向到登录页面。如果刷新页面(CTRL-R),则会进入登录页面。我怀疑问题现在与设备控制器和对AJAX / JSON的响应有关?
我是否必须更新控制器以响应(即重定向)此请求?
功能:
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"
})
}
})
}
运行功能时的日志条目:
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成功函数来重定向到登录页面。
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;
}
});
}
});
};