jQuery add CSRF token to all $.post() requests' data

前端 未结 7 1577
后悔当初
后悔当初 2020-11-30 03:02

I am working on a Laravel 5 app that has CSRF protection enabled by default for all POST requests. I like this added security so I am trying to work with it.

While m

7条回答
  •  醉酒成梦
    2020-11-30 03:42

    Your $.ajaxPrefilter approach is a good one. You don't need to add a header, though; you simply need to add a property to the data string.

    Data is provided as the the second argument to $.post, and then formatted as a query string (id=foo&bar=baz&...) before the prefilter gets access to the data option. Thus, you need to add your own field to the query string:

    var csrf_token = $('meta[name="csrf-token"]').attr('content');
    $.ajaxPrefilter(function(options, originalOptions, jqXHR){
        if (options.type.toLowerCase() === "post") {
            // initialize `data` to empty string if it does not exist
            options.data = options.data || "";
    
            // add leading ampersand if `data` is non-empty
            options.data += options.data?"&":"";
    
            // add _token entry
            options.data += "_token=" + encodeURIComponent(csrf_token);
        }
    });
    

    This will turn id=userID into id=userID&_token=csrf_token.

提交回复
热议问题