[英]how can i set a csrf token in FormData sended with XMLHttpRequest?
I'm trying to send to Django this FormData that way:我正在尝试以这种方式将此 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')
}
in Django:在 Django 中:
def my_form(request):
ob = request.POST
print('name: '+ ob['name'], 'age: '+ob['age'])
return redirect('/')
but the console gives me:但控制台给了我:
[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
What can i do to set the CSRF token in this request?我该怎么做才能在这个请求中设置 CSRF 令牌?
I figured out, i was using an embed static javascript:我想通了,我使用的是嵌入 static javascript:
<script src="{% static 'script.js' %}"></script>
the {{ csrf_token }} of the django template language just returns his value when it's in html, so the script needs to be: django 模板语言的 {{ csrf_token }} 只是在 html 中返回他的值,所以脚本需要是:
<script>
////the code here
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.