reactjs - 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: {}>`
解决方案
使用request.body
代替request.data
和代替data={request.data}
使用json.loads(request.body)
import json
print(request.body)
serializer = CreateTweeSerializers(data=json.loads(request.body))
推荐阅读
- .htaccess - 多个网站重定向
- java - 使用 Jxls-core 1.0.2 导出大量数据
- javascript - JS Jquery - 在新选项卡中打开链接
- mysql - mysql,将模式存储在其他分区/文件系统中?
- css - 悬停后如何重复css圆形动画
- angular2-services - 错误 TS2339:“可观察”类型上不存在属性“地图”
'? - laravel - Laravel 5.5 更改身份验证重置电子邮件模板
- javascript - 在输入时启动/停止 js 动画时间线的最佳方法是什么
- php - 无法在数据库中插入数据
- python - Pandas To datetime 和 Cumsum 毫秒