gpt4 book ai didi

jquery - Rails 自动更新 CSRF token 以重复 JSON 请求

转载 作者:行者123 更新时间:2023-12-01 02:53:34 25 4
gpt4 key购买 nike

我有一个包含大量远程表单的单页 ROR 应用程序。我的问题是,在非幂等请求之后,Rails 更改了 CSRF token 并使页面元中嵌入的 token 无效。因此,如果页面未刷新,重复的非幂等请求就会失败。

例如,当通过 POST 提交的远程表单因验证错误而失败并且重新提交该表单时,它会因 InvalidAuthenticityToken 错误而失败。

我认为这个问题很常见,Rails 可以默认处理它,但显然不是。

最佳答案

我的解决方案,这里有什么陷阱吗?:

application_controller.rb:

class ApplicationController < ActionController::Base
protect_from_forgery with: :exception

# callback to set CSRF TOKEN for non-idempotent Ajax request
after_action :add_csrf_token_to_json_request_header

private

def add_csrf_token_to_json_request_header
if request.xhr? && !request.get? && protect_against_forgery?
response.headers['X-CSRF-Token'] = form_authenticity_token
end
end
end

application.js:

//= require jquery2
//= require jquery_ujs
//= require turbolinks=

$( document ).ajaxComplete(function( event, xhr, settings ) {
header_token = xhr.getResponseHeader('X-CSRF-Token');
if (header_token) $('meta[name=csrf-token]').attr('content', header_token)
});

关于jquery - Rails 自动更新 CSRF token 以重复 JSON 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com