Django-----CSRF verification failed. Request aborted.

CSRF verification failed. Request aborted.

 两种方法取到cookie中的csrftoken

        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');
        var csrftoken1=$.cookie("csrftoken")
        console.log(csrftoken)
        console.log(csrftoken1)

 

解决方案一、在所有ajax发送之前统一把csrftoken参数传入

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <form action="/login.html" method="post">
 9     <p>用户名:<input id="user" type="text" name="user"></p>
10     <p>密码:<input id="pwd" type="password" name="pwd"></p>
11     <p><input type="submit" value="登录"></p>
12     <p><input id="btn" type="button" value="ajax提交"></p>
13     <span style="color: red;">{{ msg }}</span>
14     {%csrf_token%}
15 </form>
16 <script src="/static/jq/jquery-3.3.1.js"></script>
17 <script src="/static/jq/jquery.cookie.js"></script>
18 <script>
19     $(function () {
20         $.ajaxSetup({
21             beforeSend: function(xhr, settings) {
22 
23                     xhr.setRequestHeader("X-CSRFToken", csrftoken);
24 
25             }
26         });
27 
28         $("#btn").click(function () {
29             $.ajax({
30                 url:"/login.html",
31                 type:"POST",
32                 data:{'user':"root","pwd":"123123"},
33                 //header:('X-CSRFtoken',csrftoken),
34                 sucess:function (arg) {
35                     alert("ok")
36                 }
37             })
38         })
39         function getCookie(name) {
40             var cookieValue = null;
41             if (document.cookie && document.cookie !== '') {
42                 var cookies = document.cookie.split(';');
43                 for (var i = 0; i < cookies.length; i++) {
44                     var cookie = jQuery.trim(cookies[i]);
45                     // Does this cookie string begin with the name we want?
46                     if (cookie.substring(0, name.length + 1) === (name + '=')) {
47                         cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
48                         break;
49                     }
50                 }
51         }
52         return cookieValue;
53 }
54 var csrftoken = getCookie('csrftoken');
55         var csrftoken1=$.cookie("csrftoken")
56         console.log(csrftoken)
57         console.log(csrftoken1)
58 
59     })
60 </script>
61 </body>
62 </html>
View Code

解决方案二: 直接在请求头中设置

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login.html" method="post">
    <p>用户名:<input id="user" type="text" name="user"></p>
    <p>密码:<input id="pwd" type="password" name="pwd"></p>
    <p><input type="submit" value="登录"></p>
    <p><input id="btn" type="button" value="ajax提交"></p>
    <span style="color: red;">{{ msg }}</span>
    {%csrf_token%}
</form>
<script src="/static/jq/jquery-3.3.1.js"></script>
<script src="/static/jq/jquery.cookie.js"></script>
<script>

    $(function () {/*
        $.ajaxSetup({
            beforeSend: function(xhr, settings) {

                    xhr.setRequestHeader("X-CSRFToken", csrftoken);

            }
        });
        */

        $("#btn").click(function () {
            $.ajax({
                url:"/login.html",
                type:"POST",
                data:{'user':"root","pwd":"123123"},
                headers:{'X-CSRFtoken':csrftoken},
                sucess:function (arg) {
                    alert("ok")
                }
            })
        })
        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');
        var csrftoken1=$.cookie("csrftoken")
        console.log(csrftoken)
        console.log(csrftoken1)

    })
</script>
</body>
</html>
View Code

 之前一直用header 这个错误的关键词。怎么都找不到原因。翻看了jQuery用户手册才找到原因。

  

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/login.html" method="post">
    <p>用户名:<input id="user" type="text" name="user"></p>
    <p>密码:<input id="pwd" type="password" name="pwd"></p>
    <p><input type="submit" value="登录"></p>
    <p><input id="btn" type="button" value="ajax提交"></p>
    <span style="color: red;">{{ msg }}</span>
    {%csrf_token%}
</form>
<script src="/static/jq/jquery-3.3.1.js"></script>
<script src="/static/jq/jquery.cookie.js"></script>
<script src="/static/jq/js.cookie.js"></script>
<script>

    $(function () {
        /*
        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);
                }
            }
        });
        */

        $("#btn").click(function () {
            $.ajax({
                url:"/login.html",
                type:"POST",
                data:{'user':"root","pwd":"123123"},
                headers:{'X-CSRFtoken':csrftoken},
                sucess:function (arg) {
                    alert("ok")
                }
            })
        })
        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');


        var csrftoken1=$.cookie("csrftoken")
        var csrftoken2 = jQuery("[name=csrfmiddlewaretoken]").val();
        var csrftoken3 = Cookies.get('csrftoken');
        console.log(csrftoken)
        console.log(csrftoken1)
                console.log(csrftoken2)
                        console.log(csrftoken3)



    })
</script>
</body>
</html>
View Code

 

 

posted @ 2018-11-07 11:28  巨兽~墨菲特  阅读(303)  评论(0编辑  收藏  举报