[英]Forbidden (CSRF token missing or incorrect.) how to send CSRF token from frontend to backend?
I have a Django project, where I need to send a date string from frontend to backend.我有一个 Django 项目,我需要将日期字符串从前端发送到后端。 At frontend I am using the javascript fetch method
在前端,我使用的是 javascript 获取方法
async function getCustomerInDeliveryDate(deliveryDate : String) {
const response = await fetch('getCustomerInTripDate', {
method : 'POST',
headers : {
'Content-Type' : 'application/json',
},
body: JSON.stringify({
deliveryDate : deliveryDate
}),
});
return response
}
From Django backend I currently implemented a simple method that returns a string back to frontend从 Django 后端我目前实现了一个简单的方法,将字符串返回到前端
class GetCustomerInTripDate(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
print('Backend received call from front end!!!!!!!!!!!!!')
return JsonResponse({'data': ['hello', 'world']}, status = 200)
The error that I receive when I try to send to backend is我尝试发送到后端时收到的错误是
Forbidden (CSRF token missing or incorrect.): /staff/getCustomerInTripDate
I am not sure how to send the csrf token.我不确定如何发送 csrf 令牌。 The research I have done so far all indicated that credentials should be set as "same-origin", and I have tried it but still get the same error.
到目前为止我所做的研究都表明凭据应该设置为“同源”,我已经尝试过,但仍然得到同样的错误。
You just need to add {% csrf_token %}
into the template.您只需将
{% csrf_token %}
添加到模板中。
If you are using a normal HTML form, place it inside the form.如果您使用的是普通的 HTML 表格,请将其放在表格中。
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
If you are using Ajax it doesn't matter where you place it you just have to add it to the POST data如果您使用的是 Ajax 放置它并不重要,您只需将其添加到 POST 数据中
submitData = {
// other data
'csrfmiddlewaretoken': $("[name=csrfmiddlewaretoken]").val()
};
$.ajax({
method: 'post',
url: 'some_url',
data: submitData,
success: function(data){
// do things
},
error: function(event,xhr,settings,errorText){
// do error things
}
});
The error you are getting is Cross Site Request Forgery( CSRF )您得到的错误是 Cross Site Request Forgery( CSRF )
You have detailed explanation here https://docs.djangoproject.com/en/4.1/ref/csrf/你在这里有详细的解释https://docs.djangoproject.com/en/4.1/ref/csrf/
Long story short, try adding {% csrf_token %} protection in django templates.长话短说,尝试在 django 模板中添加 {% csrf_token %} 保护。
<form action="" method="post">
{% csrf_token %} <----- ADD THIS
......everything else goes here
</form>
Or if you dont use django templates try adding csrf decorator to your view.或者,如果您不使用 django 模板,请尝试将 csrf 装饰器添加到您的视图中。 I think it should be something like this:
我认为应该是这样的:
from django.utils.decorators import method_decorator<----- ADD THIS
@method_decorator(csrf_exempt, name='dispatch')<----- ADD THIS
class GetCustomerInTripDate(LoginRequiredMixin, View):
def post(self, request, *args, **kwargs):
print('Backend received call from front end!!!!!!!!!!!!!')
return JsonResponse({'data': ['hello', 'world']}, status = 200)
I think this should work, hope it helps.我认为这应该有效,希望它有所帮助。 Best regards.
此致。
The CSRF token is by default stored as a cookie. CSRF 令牌默认存储为 cookie。 So you should retrieve the cookie with javascript, then send the token it.
因此,您应该使用 javascript 检索 cookie,然后将令牌发送给它。
Or you could make a restful endpoint.或者你可以做一个安静的端点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.