我正在将React + Rails用于一个Web应用程序,并且正在将Devise用于用户身份验证。我正在努力使自定义“注销”按钮正常工作。
在我的route.rb中,我有以下内容:
devise_for :users do
delete '/users/sign_out' => 'devise/sessions#destroy' #I've also tried get instead of delete
end
我的devise.rb的配置如下:
config.sign_out_via = :delete
在我的(React)JS .jsx文件中,我具有以下注销功能,当单击按钮时会调用该功能。
function logout() {
fetch("/users/sign_out", {method: 'delete'}).then((response) => { #I have also tried replacing delete with get
}).then((result) => {
window.location.href = '/';
});
}
当我使用fetch + delete时,从fetch中得到422错误;当我使用fetch + get时,从fetch中收到404错误。我已经尝试过在route / devise.rb文件和.jsx文件之间进行get / delete的各种可能的排列,但是运气不好。
具体来说,从我的rails控制台中,我看到以下有关422错误的信息:
Can't verify CSRF token authenticity. Completed 422 Unprocessable Entity in 4ms (ActiveRecord: 0.5ms)
我的应用程序控制器具有以下内容:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :authenticate_user!
end
有趣的是,如果我做到了:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
protect_from_forgery prepend: true
before_action :authenticate_user!
end
然后422错误消失了(但是应用程序仍然像用户登录一样工作)。
答案 0 :(得分:0)
我具有相同的堆栈(redux / rails),即时获取201,不确定其是否正确,但是也许此功能将为您提供CRSF令牌:
import os
basedir = r'C:\Document'
for name in oslistdir(basedir):
fullname = os.path.join(basedir, name)
if os.path.isfile(fullname):
newname = name.replace(' ', '').lower()
if newname != name:
newfullname = os.path.join(basedir, newname)
if os.path.exists(newfullname):
print("Cannot rename " + fullname)
else:
os.rename(fullname, newfullname)
然后我在传奇中对/ users / signout的Delete请求看起来像这样:
export const getMetaContent = (name) => {
var metas = document.getElementsByTagName('meta');
for (var i=0; i<metas.length; i++) {
if (metas[i].getAttribute("name") == name) {
return metas[i].getAttribute("content");
}
}
}
// credit : https://labs.chiedo.com/post/authenticating-your-reactjs-app-with-devise-no-extra-gems-needed/