简体   繁体   English

禁止(CSRF 令牌丢失或不正确。)如何将 CSRF 令牌从前端发送到后端?

[英]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.

相关问题 在 Django 中的 ajax POST 期间禁止(CSRF 令牌丢失或不正确。) - Forbidden (CSRF token missing or incorrect.) during ajax POST in Django “禁止(CSRF 令牌丢失或不正确。):”使用 Django 和 JS - “Forbidden (CSRF token missing or incorrect.):” using Django and JS 禁止(CSRF令牌丢失或不正确。)-即使已包含 - Forbidden (CSRF token missing or incorrect.) - even though it's included 禁止(CSRF 令牌丢失或不正确。) | Django 和 AJAX - Forbidden (CSRF token missing or incorrect.) | Django and AJAX Django 和 Axios 禁止访问(CSRF 令牌丢失或不正确。) - Django and Axios Forbidden (CSRF token missing or incorrect.) 禁止(CSRF令牌丢失或不正确。)Django如何解决?用我的代码 - Forbidden (CSRF token missing or incorrect.) Django how to solve?WITH MY CODE 如何更正 django 中的以下代码,它给出错误“禁止(CSRF 令牌丢失或不正确。)” - How do I correct the following code in django, It's give an error “Forbidden (CSRF token missing or incorrect.)” 详细信息:“CSRF失败:CSRF令牌丢失或不正确。” - detail: “CSRF Failed: CSRF token missing or incorrect.” 尽管正确发送令牌,Django 服务器仍报告“禁止(CSRF 令牌丢失或不正确。)”? - Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly? 用yui设置Django CSRF_TOKEN,但控制台显示“ django.request禁止(CSRF令牌丢失或不正确。)”。 - Set Django CSRF_TOKEN with yui, but console says 'django.request Forbidden (CSRF token missing or incorrect.)'
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM