首页 > 解决方案 > Django / Fetch:从请求的数据流中读取后无法访问正文

问题描述

我正在使用 REST API,目前正在将数据从 fetch 发送到我的 django 视图。从请求的数据流中读取后,我无法访问正文。怎么了?

PS:我已经尝试过使用request.data,但出现了一些其他问题

视图.py

@csrf_exempt 
@api_view(['POST'])
def createNew(request):
    data = json.loads(request.body)
    if request.method == 'POST':
        serializer = newsSerializer(data =data['title'])
        if serializer.is_valid():
            serializer.save()
            # return Response(serializer.data)
            return redirect('http://127.0.0.1:8000/news_list/')

我的获取方法

form.addEventListener("submit", function(e) {
            e.preventDefault()
            var url = 'http://127.0.0.1:8000/news_create/'
            var title = document.getElementById('title').value

            fetch(url, {
                    method: 'POST', // or 'PUT'
                    headers: {
                        'Accept': 'application/json, text/plain, */*',
                        'Content-Type': 'application/json',
                        'X-CSRFToken': csrftoken,
                    },
                    body: JSON.stringify({
                        'title': title
                    }),
                })
                .then(response => response.json())
                .then(data => {
                    console.log('Success:', data);
                })
                .catch((error) => {
                    console.error('Error:', error);
                });

        });

标签: jsondjangorestfetch

解决方案


推荐阅读