I am trying to create an API on my Django server but I am struggling to create a post method called by Javascript.
This is my APIview
class componentFrameAPI(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.
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.
NOTE: The GET method works fine.
Thanks for your help.
Giacomo
Advertisement
Answer
Your are close but have a typo in 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)