【问题标题】:Django - AJAX POST to API not working but no errorsDjango - AJAX POST 到 API 不起作用但没有错误
【发布时间】:2020-03-19 17:30:26
【问题描述】:

我正在尝试将数据发布到我的 Django Rest Framework API,我有一个有效的 GET 请求。 POST 请求不起作用,并触发 AJAX 调用的错误函数。我似乎不明白为什么它不起作用,也许我的 CSRF 或 CORS 标头不正确?

ma​​in.js

$(function () {

  var $items = $('#items');
  var $description = $('#description');
  var $price = $('#price');

   $.ajax({
     type: 'GET',
     url: '/api',
     success: function(items) {
       console.log(items)
       $.each(items,function(i, item){
         $items.append('<li> '+ item.pk +', '+ item.Description +', '+ item.Price +'</li>');
       });
     },
     error: function() {
       alert('Error Loading Items');
     }
   });

   $('#add-item').on('click', function() {

     var order = {
       description: $description.val(),
       price: $price.val(),
     };

     $.ajax({
       type: 'POST',
       csrfmiddlewaretoken: "{{ csrf_token }}",
       url: '127.0.0.1:8000/api/',

       data: order,

       success: function(newItem) {
         $items.append('<li> '+ newItem.Description +', '+ newItem.Price +'</li>');
       },
       error: function() {
         console.log(order)
       }
     });

   });


});

models.py

class Item(models.Model):
    Description = models.CharField(max_length=20)
    Price = models.DecimalField(max_digits=5, decimal_places=2)

    def __str__(self):
        return self.Description

序列化器 Views.py

class ItemListAPIView(generics.ListCreateAPIView):
    lookup_field = 'pk'
    queryset = Item.objects.all()
    serializer_class = ItemSerializer
    permission_classes = (AllowAny,)

【问题讨论】:

    标签: jquery django ajax api django-rest-framework


    【解决方案1】:

    发布请求需要 X-CSRF-TOKEN 标头设置正确的令牌 - 这就是为什么 get 请求通过(我假设),但 post 不是。

    您不能在 javascript 文件中使用 django 模板语言 ({{ csrf_token }}),因为它不会呈现为实际令牌 - 它只会传递字符串文字 '{{ csrf_token }}'

    你可以像这样在django docs的帮助下获取实际令牌,假设authentication is set by default

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = cookies[i].trim();
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    
    $.ajax({
        type: 'POST',
        headers: {
            'X-CSRF-TOKEN': getCookie('csrftoken'),
            'Content-Type': 'application/json'
        },
        url: '127.0.0.1:8000/api/',
    
        data: order,
    
        success: function (newItem) {
            $items.append('<li> ' + newItem.Description + ', ' + newItem.Price + '</li>');
        },
        error: function () {
            console.log(order)
        }
    });
    

    【讨论】:

    • 感谢您的回答。我试过你的解决方案。不幸的是,它仍然不起作用。非常不确定可能是什么问题。
    • 通过您的浏览器开发者控制台检查您的服务器响应的答案是什么。这将有助于理解这里出了什么问题。
    猜你喜欢
    • 1970-01-01
    • 2014-04-26
    • 2016-04-17
    • 2021-10-14
    • 1970-01-01
    • 2019-01-26
    • 2013-10-01
    • 2018-04-08
    • 1970-01-01
    相关资源
    最近更新 更多