Adding CSRFToken to Ajax request

后端 未结 9 2056
夕颜
夕颜 2020-11-27 05:40

I need to pass CSRFToken with Ajax based post request but not sure how this can done in a best way. Using a platform which internally checking CSRFToken

9条回答
  •  孤城傲影
    2020-11-27 06:17

    The answer above didn't work for me.

    I added the following code before my ajax request:

    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;
                }
                var csrftoken = getCookie('csrftoken');
    
                function csrfSafeMethod(method) {
                    // these HTTP methods do not require CSRF protection
                    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
                }
    
                $.ajaxSetup({
                    beforeSend: function(xhr, settings) {
                        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                            xhr.setRequestHeader("X-CSRFToken", csrftoken);
                        }
                    }
                });
    
                $.ajax({
                         type: 'POST',
                         url: '/url/',
                });
    

提交回复
热议问题