[英]415 UNSUPPORTED MEDIA - API Post Javascript - Django
I am trying to create an API on my Django server but I am struggling to create a post method called by Javascript.我正在尝试在我的 Django 服务器上创建一个 API,但我正在努力创建一个由 Javascript 调用的 post 方法。
This is my APIview这是我的 API 视图
class componentFrameAPI(APIView): class 组件FrameAPI(APIView):
def get(self, request):
componentAPI = component.objects.all()
serializer = componentSerializer(componentAPI, many=True)
return Response(serializer.data)
def post(self):
serializer = componentSerializer(componentAPI, data=self.data)
if serializer.is_valid():
# serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
And this is my post request on Javascript.这是我对 Javascript 的发帖请求。
let data = {componentName:"PostTest",componentBody:"TEST"}
datax = JSON.stringify(data)
var xhttp = new XMLHttpRequest()
xhttp.open("POST","http://127.0.0.1:8000/myurl/", true)
xhttp.setRequestHeader('X-CSRFToken', csrftoken)
xhttp.setRequestHeader('contentType', 'application/json')
xhttp.send(datax)
I continue to receive a 415 error and I really don't know what I am doing wrong.我继续收到 415 错误,我真的不知道我做错了什么。
NOTE: The GET method works fine.注意: GET 方法工作正常。
Thanks for your help.谢谢你的帮助。
Giacomo贾科莫
Your are close but have a typo in xhttp.setRequestHeader('contentType', 'application/json')
你很接近,但在xhttp.setRequestHeader('contentType', 'application/json')
中有错字
Change that to将其更改为
xhttp.setRequestHeader('Content-Type', 'application/json')
And you should be fine Full example你应该没问题 完整的例子
let data = {componentName:"PostTest",componentBody:"TEST"}
datax = JSON.stringify(data)
var xhttp = new XMLHttpRequest()
xhttp.open("POST","http://127.0.0.1:8000/myurl/", true)
xhttp.setRequestHeader('X-CSRFToken', csrftoken)
xhttp.setRequestHeader('Content-Type', 'application/json')
xhttp.send(datax)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.