无法使用脚本

问题描述

我正在使用 Rails 5.2.5 开发一个项目,并尝试使用 actionpack-page_caching 缓存静态页面。我在这里和那里遇到了一些问题,比如 topnav 被缓存,但我使用 AJAX 解决了它们。现在我正在处理 CSRF 保护参数和缓存的令牌,因为此令牌与每个用户的会话不同。

我从 here 中阅读了解决方案。我尝试通过 XHR 发送令牌。目前获取CSRF保护参数和token的动作是这样的。

def csrf_Meta
  respond_to do |format|
    format.json do
      render json: {
        param: request_forgery_protection_token,token: form_authenticity_token
      }
    end
  end
end

此操作位于 ApplicationController 中,可以通过 /csrf_Meta 路径检索。现在获取这个的脚本放在 <head> 中:

$(document).on('turbolinks:load',() => {
  $.getJSON('<%= csrf_Meta_path format: :json %>').then((json) => {
    if (!$('Meta[name="csrf-param"]').length)
      $('<Meta>')
        .attr('name','csrf-param')
        .attr('content',json.param)
        .appendTo('head');
    else
      $('Meta[name="csrf-param"]').attr('content',json.param);

    if (!$('Meta[name="csrf-token"]').length)
      $('<Meta>')
        .attr('name','csrf-token')
        .attr('content',json.token)
        .appendTo('head');
    else
      $('Meta[name="csrf-token"]').attr('content',json.token);
  });
});

我也删除了应用程序布局中的 <%= csrf_Meta_tags %>

登录用户将启动 POST /users/sign_in 并检索 JS 响应以在模态中显示登录表单。登录表单是远程的,这意味着异步处理,因此从 Rails 生成的 HTML 不会在表单内提供 authenticity_token 输入。据我所知,UJS 将从元标记获取令牌。尝试登录后,响应代码为 422,服务器显示“无法验证 CSRF 令牌的真实性。”

我已经将 action_view.embed_authenticity_token_in_remote_forms 配置设置为 true,它解决了这个问题。但是要注销,用户需要按此按钮:

<a data-remote="true" rel="nofollow" data-method="delete" href="/users/sign_out">logout</a>

此按钮没有任何 authenticity_token 参数要发送,因此在尝试注销后,服务器发送代码 422 和“无法验证 CSRF 令牌真实性”消息。

我已经尝试在没有 <body> 事件的情况下在开始时将脚本内联到 turbolinks:load 标记中,但仍然没有解决问题。

有什么解决办法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)