ActionController::InvalidAuthenticityToken 禁用 JS/Ajax 请求时 [英] ActionController::InvalidAuthenticityToken when disable JS/Ajax request

查看:47
本文介绍了ActionController::InvalidAuthenticityToken 禁用 JS/Ajax 请求时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两种带有选项 remote: true 的表单;一个向 create 动作发送 Ajax 请求,另一个向 destroy 动作发送 Ajax 请求.

I have two forms with option remote: true; one sends an Ajax request to create action and the other one sends an Ajax request to destroy action.

启用 JavaScript 时一切正常,但如果我禁用 JavaScript,然后单击,我会收到此错误:

All work fines when JavaScript is enabled, but if I disable JavaScript, then I click, I get this error:

ActionController::InvalidAuthenticityToken PersonsController#create

为什么会显示此错误,我该如何解决?

Why this error is shown, and how can I fix it ?

注意:我使用的是 Rails 4

note: I'm using Rails 4

当我使用没有选项 remote: true 的普通表单时,rails 会自动为身份验证令牌插入一个隐藏字段,但是当我在表单中使用 remote: true 时HTML 代码中没有这样的字段.似乎当有 remote 选项时,Rails 会以不同的方式处理身份验证令牌,那么我如何才能让它在两种情况下都能正常工作?

When I use a normal form without option remote: true, rails automatically inserts a hidden field for an authentication token, but when I use remote: true in my form there is no such field in the HTML code. It seems like when there is remote option, then Rails handles the authentication token differently, so how I can get this to work in both cases?

推荐答案

奇怪的是,这种行为在 rails 4 中发生了变化.http://www.alfajango.com/blog/rails-4-whats-new/

Bizarrely, this behaviour was changed in rails 4. http://www.alfajango.com/blog/rails-4-whats-new/

Rails 表单现在不会在表单中呈现 CSRF 字段,除非您明确将其定义为表单的选项:

Rails forms now will not render the CSRF field in the form unless you explicitly define it as an option to your form:

<%= form_for @some_model, :remote => true, :authenticity_token => true do |f| %>
<% end %>

添加此选项可让您在 Javascript 关闭时优雅地降级为 HTML 回退.

Adding this option allows you to gracefully degrade to a HTML fallback if Javascript is switched off.

这篇关于ActionController::InvalidAuthenticityToken 禁用 JS/Ajax 请求时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆