繁体   English   中英

正文未发布在 Django Rest API 调用中使用 Z9E13B69D1D2DA927102ACAAAFZ715

[英]Body not Posting in Django Rest API call using Javascript fetch

我在我的 Node.js 应用程序中使用 Django RestFramework API。 我正在使用 Javascript fetch API 将一些数据发送到我在 Django 中配置的项目的后端。 但是数据没有发布。 它在 PostMan 中运行良好,但不使用 fetch。

我的 API class 如下:

class ProfileList(APIView):

    def get(self, request):
        ProfileObjects = Profile.objects.all()
        serializer = ProfileSerializer(ProfileObjects, many=True)
        return Response(serializer.data)

    def post(self, request, **kwargs):
        print(request.POST)
        print(self.request.POST)
        ProfileObjects = Profile.objects.all()
        serializer = ProfileSerializer(ProfileObjects, many=True)
        return Response(serializer.data)

fetch 调用看起来像这样..:

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 = jQuery.trim(cookies[i]);
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('csrftoken');

fetch('http://127.0.0.1:8000/API/', {
    method: 'post',
    headers: {
        'Accept': 'application/json, text/plain, */*',
        'Content-Type': 'application/json',
        'X-CSRFToken': csrftoken,
    },
    body: JSON.stringify({data: "your data"})
}).then(res => res.json())
    .then(res => console.log(res));

那么根据 API class 视图它应该打印{data: "your data"}但它不是。 相反,这是在使用 fetch 调用时打印出来的

<QueryDict: {}>
<QueryDict: {}>
HTTP POST /API/ 200 [0.01, 127.0.0.1:62136]

当我将它与 postman 一起使用时,它会被打印出来..

<QueryDict: {'data': ['your data']}>
<QueryDict: {'data': ['your data']}>
HTTP POST /API/ 200 [0.01, 127.0.0.1:62358]

csrftoken header 应该是X-CSRFToken ,如下所示 -

headers: {'X-CSRFToken': csrftoken}

试试这个并检查,你可以在这里看到文档

对于解析请求,在 DRF 中我们应该使用request.data而不是request.POST

此处检查 DRF 中的请求解析

class ProfileList(APIView):

    def get(self, request):
        ProfileObjects = Profile.objects.all()
        serializer = ProfileSerializer(ProfileObjects, many=True)
        return Response(serializer.data)

    def post(self, request, **kwargs):
        print(request.POST) // will not work
        print(request.data) // will work
        ProfileObjects = Profile.objects.all()
        serializer = ProfileSerializer(ProfileObjects, many=True)
        return Response(serializer.data)

主要问题是我使用 request.POST 而不是 request.data 访问正文

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM