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):
JavaScript
x
12
12
1
def get(self, request):
2
componentAPI = component.objects.all()
3
serializer = componentSerializer(componentAPI, many=True)
4
return Response(serializer.data)
5
6
def post(self):
7
serializer = componentSerializer(componentAPI, data=self.data)
8
if serializer.is_valid():
9
# serializer.save()
10
return Response(serializer.data, status=status.HTTP_201_CREATED)
11
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
12
And this is my post request on Javascript.
JavaScript
1
9
1
let data = {componentName:"PostTest",componentBody:"TEST"}
2
datax = JSON.stringify(data)
3
4
var xhttp = new XMLHttpRequest()
5
xhttp.open("POST","http://127.0.0.1:8000/myurl/", true)
6
xhttp.setRequestHeader('X-CSRFToken', csrftoken)
7
xhttp.setRequestHeader('contentType', 'application/json')
8
xhttp.send(datax)
9
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
JavaScript
1
2
1
xhttp.setRequestHeader('Content-Type', 'application/json')
2
And you should be fine Full example
JavaScript
1
9
1
let data = {componentName:"PostTest",componentBody:"TEST"}
2
datax = JSON.stringify(data)
3
4
var xhttp = new XMLHttpRequest()
5
xhttp.open("POST","http://127.0.0.1:8000/myurl/", true)
6
xhttp.setRequestHeader('X-CSRFToken', csrftoken)
7
xhttp.setRequestHeader('Content-Type', 'application/json')
8
xhttp.send(datax)
9