2

在我的 Rails 应用程序中,即使页面未刷新且浏览器未关闭,csrf_meta_tags 也会为每个 ajax 请求生成新令牌。

这是我的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

阿贾克斯设置

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

0 回答 0