即使在我成功设置X-CSRF-Token标头后,也会出现导轨401错误

时间:2013-04-26 16:09:31

标签: ruby-on-rails-3 jquery-validate csrf

我正在制作一个注册表单,并希望使用jquery-validation插件来检查user_name是否唯一。

路线:

resources :users, :only => [:show] do
  collection do                      
    post 'check_user_name_uniq'     
    get 'check_email'                
    get 'check_password'             
  end  

控制器:

def check_user_name_uniq
  render :json => User.valid_attribute?(:user_name, params[:user][:user_name]).to_json
end

的javascript:

$("#new_user").validate({
  debug: true,
  rules: {
    "user[user_name]": {
      required: true,           
      remote: {
        url:  "/users/check_user_name_uniq", // check user_name uniqueness
        type: "POST",
        dataType: "json"
      }
    }                                        
  },...

我通过以下方式设置X-CSRF-Token标头:

$.ajaxSetup({
  beforeSend: function(jqXHR) {
    jqXHR.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
  }
});

但是当我输入user_name时,仍然有401错误:

Started POST "/users/check_user_name_uniq" for 192.168.157.1 at 2013-04-26 23:52:22 +0800
Processing by UsersController#check_user_name_uniq as JSON
  Parameters: {"user"=>{"user_name"=>"tomwang"}}
Completed 401 Unauthorized in 36ms

我不知道为什么会发生这个错误,因为他们说标题可以解决它: WARNING: Can't verify CSRF token authenticity rails

1 个答案:

答案 0 :(得分:0)

您确定布局中存在<%= csrf_meta_tags %>吗?