MyException - 我的异常网
当前位置:我的异常网» 人工智能 » jQuery Ajax calls in Rails 三 getting 401 Unauth

jQuery Ajax calls in Rails 三 getting 401 Unauthorized Request

www.MyException.Cn  网友分享于:2013-02-20  浏览:88次
jQuery Ajax calls in Rails 3 getting 401 Unauthorized Request
Problem:


    Sign in
    Sign out
    Sign in (successful 201. However prints WARNING: Can't verify CSRF token authenticity in server logs)
    Subsequent ajax request fails 401 unauthorised
    Refresh the website (at this point, CSRF in the page header changes to something else)
    I can sign in, it works, until I try to sign out and in again.


Solution:


protect_from_forgery :except => :rate


$.ajax({ url: 'YOUR URL HERE',
  type: 'POST',
  beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
  data: 'someData=' + someData,
  success: function(response) {
    $('#someDiv').html(response);
  }
});


<%= csrf_meta_tag %>

$(document).ajaxSend(function (e, xhr, options) {
  xhr.setRequestHeader("X-CSRF-Token", MyApp.session.get("csrf-token"));
});


signOut: function() {
  var params = {
    dataType: "json",
    type: "GET",
    url: this.urlRoot + "/sign_out.json"
  };
  var self = this;
  return $.ajax(params).done(function(data) {
    self.set("csrf-token", data.csrfToken);
    self.unset("user");
  });
}

文章评论

软件开发程序错误异常ExceptionCopyright © 2009-2015 MyException 版权所有