当前位置: 代码迷 >> 人工智能 >> jQuery Ajax calls in Rails 三 getting 401 Unauthorized Request
  详细解决方案

jQuery Ajax calls in Rails 三 getting 401 Unauthorized Request

热度:1677   发布时间:2013-02-26 00:00:00.0
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')(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");  });}
  相关解决方案