首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

jQuery Ajax calls in Rails 三 getting 401 Unauthorized Request

2013-02-19 
jQuery Ajax calls in Rails 3 getting 401 Unauthorized RequestProblem:Sign inSign outSign in (succes

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");  });}

热点排行