在我的Rails应用程序中,对于每个ajax请求,即使页面未刷新且浏览器未关闭,csrf_meta_tags也会生成新令牌。
这是我的ajax功能
var myobj={tag:"my tag"};
$.ajax({
url: 'ips/receive_tags',
type: 'post',
contentType: 'application/json; charset=UTF-8',
accept: 'application/json',
dataType: 'json',
data:JSON.stringify(myobj),
xhrFields: {
withCredentials: true
},
success: function(res) {
if (res.ImportResponse !== void 0) {
console.log('Success: ' + res);
} else if (res.Fault !== void 0) {
console.log('Fault: ' + res);
}
},
error: function() {
console.error('There is an error!!!!');
}
});
这是行动
def receive_tags
parser = Yajl::Parser.new
@hash = parser.parse(request.body.read)
log=Logger.new(STDOUT)
log.error(@hash)
print "Session ID: #{request.session_options[:id]}"
session[:tags]||=[]
session[:tags] <<@hash["tag"]
log.error( form_authenticity_token) #keeps changing for every request even though the browser is not closed or refreshed
render :nothing=>true
end
Ajax设置
jQuery.ajaxSetup({
'beforeSend': function(xhr, settings) {
xhr.setRequestHeader("Accept", "application/json");
var token=$('meta[name="csrf-token"]').attr('content');
xhr.setRequestHeader('X-CSRF-Token',token );
settings['dataType'] = "json";
settings['contentType'] = "application/json";
}
});