【发布时间】:2021-03-14 11:53:17
【问题描述】:
在打字稿方面,我有这个应该发送发布请求的代码。
请注意,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: {}>`
【问题讨论】:
-
你可以试试 request.post 吗?或打印请求?
-
是的,是一样的
-
stackoverflow.com/questions/34532573/… 你应该试试 request.body 并可能改变你的 '{"content":"new text"}'
-
我可以发布答案并获得积分吗? ;)
标签: reactjs django django-rest-framework django-react