首页 > 解决方案 > xhr.send() 发布请求不传递数据

问题描述

在打字稿方面,我有这个应该发送发布请求的代码。请注意,getCookie函数是从 Django 文档中复制的,就像它一样。

const xhr = new XMLHttpRequest();
  xhr.responseType = "json";
  xhr.open("POST", `http://localhost:8000/create/`);
  xhr.setRequestHeader("Content-Type", "application/json");
  const coockie = getCookie("csrftoken");
  if (coockie) {
    xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest");
    xhr.setRequestHeader("X-Requested-with", "XMLHttpRequest");
    xhr.setRequestHeader("X-CSRFToken", coockie);
  }
  xhr.onload = function () {
    callback(xhr.response, xhr.status);
  };
  xhr.onerror = function (e) {
    console.log(e);
    callback({ message: "The request was an error" }, 400);
  };
  xhr.send('{"content":"new text"}');

在views.py中


@api_view(["POST"])
@permission_classes([IsAuthenticated])
def post_create_view(request, *args, **kwargs):
    print(request.data)
    serializer = CreateTweeSerializers(data={request.data})
    # raise_exception= if form.error reutnr error and status400
    if serializer.is_valid(raise_exception=True):
        serializer.save(user=request.user)
        return Response(serializer.data, status=201)
    return Response({}, status=400)
`print(request.data)` or `print(request.POST)` return `<QueryDict: {}>`

标签: reactjsdjangodjango-rest-frameworkdjango-react

解决方案


使用request.body代替request.data 和代替data={request.data}使用json.loads(request.body)

import json
    print(request.body)
    serializer = CreateTweeSerializers(data=json.loads(request.body))


推荐阅读