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

前端 未结 7 1580
后悔当初
后悔当初 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:38

    no need to set any meta tag neither the csrf_token() nor the csrf_field() !

    You could use this jQuery snippet :

    $.ajaxPrefilter(function( settings, original, xhr ) {
        if (['post','put','delete'].includes(settings.type.toLowerCase())
            && !settings.crossDomain) {
                xhr.setRequestHeader("X-XSRF-TOKEN", getCookie('XSRF-TOKEN'));
        }
    });
    
    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    

    just few other answers tried to set the csrf header but according the Laravel documents (here) , the header key should be "X-XSRF-TOKEN" and Laravel itself provides the needed value on every request for us in a cookie named "XSRF-TOKEN"

    so just corrected the keys and edited few lines,thanks

提交回复
热议问题