如何在XMLHttpRequest发送的FormData中设置csrf令牌?

时间:2020-06-30 23:32:22

标签: javascript django xmlhttprequest

我正尝试通过以下方式将这个FormData发送给Django:

const form = new FormData()

form.append('name','Vitor')
form.append('age',20)
form.append('csrfmiddlewaretoken', '{{ csrf_token }}');

const request = new XMLHttpRequest()
request.open('POST','my_form')
request.send(form)

request.onload = function(){
 alert('sucess')   
}
request.onerror = function(){
    alert('error')   
   }

在Django中:

def my_form(request):
    ob = request.POST
    print('name: '+ ob['name'], 'age: '+ob['age'])
    return redirect('/')

但是控制台给了我

[30/Jun/2020 20:27:12] "GET / HTTP/1.1" 200 419
[30/Jun/2020 20:27:12] "GET /static/script.js HTTP/1.1" 200 352
Forbidden (CSRF token missing or incorrect.): /my_form
[30/Jun/2020 20:27:12] "POST /my_form HTTP/1.1" 403 2513

该如何设置此请求中的CSRF令牌?

1 个答案:

答案 0 :(得分:0)

我发现,我使用的是嵌入的静态javascript:

<script src="{% static 'script.js' %}"></script>

django模板语言的{{csrf_token}}仅在html中时才返回其值,因此脚本必须为:

<script>
////the code here
</script>