2015-07-03 101 views
4

我有一个页面上有两种形式,两者都声明如下:CSRF令牌多种形式

form_for @student, {remote:true, format: 'json'} do |f|

form_for @teacher, {remote:true, format: 'json'} do |f|

然而,当我点击提交teacher表单的按钮时,它会出错,并为该请求提供“无效的CRSF令牌”。请求student表单工作正常。

我在application.html.erb文件中获得<%= csrf_meta_tags %>teacher表单在提交中确实有CSRF令牌。我没有做API,我只是想通过AJAX处理表单(我做了一些客户端错误处理和确认)。

回答

1

你需要禁用JSON请求CSRF保护,根据Rails的文档:http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

重要的是要记住,XML或JSON请求也受到影响 ,如果你正在构建的API是非常重要的你需要这样的东西:

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    skip_before_action :verify_authenticity_token, if: :json_request? 

    protected 

    def json_request? 
    request.format.json? 
    end 
end 

参见:

+0

嗯有意思,我从来不知道。它现在可以工作,所以非常感谢你! – docaholic