Two ajax requests, 2 csrf tokens one for POST one for PUT not working - 403 error

江枫思渺然 提交于 2019-12-13 03:59:57

问题


I have 2 $.ajax() functions in one html rendered by Django. The first one works correctly, the second one answers with a 403 CSRF Failed: CSRF token missing or incorrect.

This is the relevant js code:

$(document).ready(function(){

   window.CSRF_TOKEN = "{{ csrf_token }}";

    ....
    $.ajax({
           method: "POST",
           url: "{% url 'alpha:create_cart_item' %}",
           data: {'item': stockitem_id, 'quantity': '1', 'csrfmiddlewaretoken': window.CSRF_TOKEN},
           success: function(resp){...}

    ....
    $.ajax({
           method: "PUT",
           url: "{% url 'alpha:update_cart_item' 0 %}".replace("0", cartitem_id),
           data: {'pk': cartitem_id, 'csrfmiddlewaretoken': window.CSRF_TOKEN},
           success: function(resp){
               panel_div.hide();
           },
           error: function(resp){
           }
       });

The second Ajax request is not working. I set the csrfmiddlewaretoken in the exact same way. Why am I getting the 403?. Obviously I'm missing something, please help.

UPDATE

Debugging this I found out that if I change the method o the 2nd request to "POST", it works correctly. But I do need the method to be "PUT".

Also, I'm using Django REST Framework...

来源:https://stackoverflow.com/questions/39520340/two-ajax-requests-2-csrf-tokens-one-for-post-one-for-put-not-working-403-erro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!