zoukankan      html  css  js  c++  java
  • Django Ajax请求的403问题

    问题原因:

    Django的跨站请求伪造中间件:POST请求中缺少csrftoken参数和相关的值。
    问题排查:登陆后才会具有csrftoken;ajax中放在`header`中
    

    参考连接:

    https://docs.djangoproject.com/en/3.1/ref/csrf/#ajax
    

    代码参考:

    <script>
        function getCookie(name) {
                let cookieValue = null;
                if (document.cookie && document.cookie !== '') {
                    const cookies = document.cookie.split(';');
                    for (let i = 0; i < cookies.length; i++) {
                        const cookie = cookies[i].trim();
                        // 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;
            }
    
    
            function add_data() {
                const csrftoken = getCookie('csrftoken');
    
                $.ajax({
                    headers: {'X-CSRFToken': csrftoken},
                    url: "{% url 'add' %}",
                    type: "POST",
                    data: {"type": "{{ type }}", "data": 1},
    
                    success: function (result) {
                        if (result.code === 200) {
                            console.log(result.msg)
                        }
                        console.log(result)
                    },
                    fail: function (result) {
                        console.log(result)
                    },
                });
            }
    </script>
    
    
  • 相关阅读:
    1203 有穷自动机
    1111 评论
    C语言文法 改
    用户调研
    阅读《构建之法》 第8 第9 第10章
    sprint冲刺(第二天)
    sprint初步计划(第一天)
    作业6 团队项目之需求
    作业5 四则运算 测试与封装 5.1 5.2
    作业5 四则运算 测试与封装 5.1
  • 原文地址:https://www.cnblogs.com/lisicn/p/14313182.html
Copyright © 2011-2022 走看看