[英]Why do I get a 'CSRF token missing or incorrect' error?
I am trying to return a value from a View function in Django. 我试图从Django中的View函数返回一个值。 That function is being called from a JavsScript code using Ajax, but I get thrown an error which reads 'Forbidden (CSRF token missing or incorrect)'.
该函数是使用Ajax从JavsScript代码中调用的,但是我抛出了一个错误,显示为“禁止(CSRF令牌丢失或不正确)”。
JavaScript/Ajax 的JavaScript / AJAX
The HTML code looks something like this: HTML代码如下所示:
<div align="center" class="input-line">
<form class="input-form" method="post">{% csrf_token %}
<input type = "text" id = "ans" class = "form-control" name = "address" placeholder="Type postcode..."><br><br>
<button id = "homeBtn" class="btn btn-primary">Find info</button><br><br>
</form>
</div>
The View Function is: 查看功能是:
def result(request):
if(request == 'POST'):
param = request.form['my data']
this = runAreaReview(param) #This returns a string
return HttpResponse(this)
method 1 方法1
For making post requests with ajax, you need to set a header called HTTP_X_CSRFTOKEN
and set it's value to a cookie which is stored in the browser by name csrftoken
. 为了使用ajax发出发布请求,您需要设置一个名为
HTTP_X_CSRFTOKEN
的标头,并将其值设置为cookie,该cookie以名称csrftoken
形式存储在浏览器中。 Reference . 参考 。 so in your ajax call, you should do something like this.
因此在ajax调用中,您应该执行以下操作。
var csrftoken = Cookies.get('csrftoken');
$.ajax(
...
headers:{"HTTP_X_CSRF_TOKEN":csrftoken}
);
also note that if you are using some reverse proxy server with something like nginx, make sure to froward this header as well to the django application. 还请注意,如果您将反向代理服务器与诸如nginx之类的产品一起使用,请确保将该标头也转发给django应用程序。
method 2 方法2
you can disable csrf verification for this specific view by using an annotation. 您可以使用注释为该特定视图禁用csrf验证。 Reference
参考
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def result(request):
...
method 3 方法3
The method below is NOT RECOMMENDED for security reasons 出于安全原因,不建议使用以下方法
You can alwaws turnoff the csrf middleware in settings to get rid of it if you are just building something for recreational purpose and not for production. 如果您只是出于娱乐目的而不是用于生产目的,则可以在设置中关闭csrf中间件以摆脱它。
对于遇到此线程的任何人,HEADER密钥应为Django 2.1的X-CSRFToken
,链接在此处https://docs.djangoproject.com/en/2.1/ref/csrf/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.