简体   繁体   English

AJAX 的 CSRF 令牌丢失或不正确

[英]CSRF token missing or incorrect with AJAX

I have followed this tutorial and defined my form as below:我已遵循本教程并将我的表单定义如下:

    <form action="" id="contactForm" method="post" role="form" class="contact-form">
    {% csrf_token %}
    ...

views.py:视图.py:

def contact(request):
    if request.is_ajax():
        sender_name = request.POST.get('sender_name')
        sender_email = request.POST.get('sender_email')
        message_subject = request.POST.get('message_subject')
        message_text = request.POST.get('message_text')

        html_message = render_to_string('contact.html', {'sender_name': sender_name, 'sender_email': sender_email, 'message_subject': message_subject, 'message_text': message_text})

        email_subject = 'Message Subject'
        email_from = 'My Name'
        email_to = ['me@mydomain.com',]

        send_mail(email_subject, '', email_from, email_to, html_message=html_message)

        response = {}

        return JsonResponse(response)

AJAX code: AJAX 代码:

$('#contactForm').submit(function(e){
    e.preventDefault()

    $('#loading').css("display", "block")

    $.ajax({
        type : "POST",
        url : "/contact/",
        data: {
            sender_name : $('#name').val(),
            sender_email : $('#email').val(),
            message_subject : $('#subject').val(),
            message_text : $('#message').val(),
            csrfmiddlewaretoken : '{{ csrf_token }}',
            datatype : "json",
        },

        success: function(){
            $('#loading').css("display", "none"),
            $('#sent-message').css("display", "block")
        },
    });
});

However, I get the annoying "CSRF token missing or incorrect" error after submitting the form.但是,在提交表单后,我收到烦人的“CSRF 令牌丢失或不正确”错误。

Please assist.请协助。

EDIT:编辑:

I moved the AJAX code from external JS file to the index.html and it worked!我将 AJAX 代码从外部 JS 文件移动到 index.html 并且它起作用了! So it seems {% csrf_token %} is not available to my JS file.所以似乎{% csrf_token %}不适用于我的 JS 文件。 Why is that and how to solve it?为什么会这样以及如何解决?

have you tried attaching your csrf like this你试过像这样附加你的csrf吗

To embed a csrf token in each AJAX request, for jQuery it may be:要在每个 AJAX 请求中嵌入 csrf 令牌,对于 jQuery,它可能是:

$(function () { $(函数(){

   $.ajaxSetup({
      headers: { "X-CSRFToken": getCookie("csrftoken") }
   });

});

According to this from original Django docs, you need to implement the function getCokie(name) as:根据原始Django文档,您需要将 function getCokie(name)实现为:

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;
    }

And then you set the headers as:然后将标题设置为:

$.ajaxSetup({
   headers:{
      'X-CSRFToken': getCookie("csrftoken")
   }
});

I was implementing it today, and it worked, I was using reactJs and was making the request by using XMLHttpRequest() but it should be very similar.我今天正在实现它,它起作用了,我使用的是 reactJs 并使用XMLHttpRequest()发出请求,但它应该非常相似。

var el = document.getElementsByName("csrfmiddlewaretoken");
csrf_value = el[0].getAttribute("value");

then in your data然后在你的数据中

'csrfmiddlewaretoken' : csrf_value,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM