Adding CSRFToken to Ajax request

后端 未结 9 2134
夕颜
夕颜 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:05

    Here is code that I used to prevent CSRF token problem when sending POST request with ajax

    $(document).ready(function(){
        function getCookie(c_name) {
            if(document.cookie.length > 0) {
                c_start = document.cookie.indexOf(c_name + "=");
                if(c_start != -1) {
                    c_start = c_start + c_name.length + 1;
                    c_end = document.cookie.indexOf(";", c_start);
                    if(c_end == -1) c_end = document.cookie.length;
                    return unescape(document.cookie.substring(c_start,c_end));
                }
            }
            return "";
        }
    
        $(function () {
            $.ajaxSetup({
                headers: {
                    "X-CSRFToken": getCookie("csrftoken")
                }
            });
        });
    

    });

提交回复
热议问题