【发布时间】:2020-12-05 16:39:41
【问题描述】:
我在我的 Node.js 应用程序中使用 Django RestFramework API。 我正在使用 Javascript 获取 API 将一些数据发送到我在 Django 中配置的项目的后端。 但是数据没有发布。它在 PostMan 中运行良好,但不使用 fetch。
我的API类如下:
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 类视图,它应该打印 {data: "your data"},但事实并非如此。
相反,这是在使用 fetch 调用时打印出来的
<QueryDict: {}>
<QueryDict: {}>
HTTP POST /API/ 200 [0.01, 127.0.0.1:62136]
当我将它与邮递员一起使用时,它会被打印出来..
<QueryDict: {'data': ['your data']}>
<QueryDict: {'data': ['your data']}>
HTTP POST /API/ 200 [0.01, 127.0.0.1:62358]
【问题讨论】:
标签: javascript python django django-rest-framework fetch