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>

原文地址:https://www.cnblogs.com/lisicn/p/14313182.html