I'm trying to do a post call from react application using below code.
const postchart = async () => {
const data = {
name: name,
day: startDate.getDate(),
expense: amount
}
const request = {
method : 'POST',
mode: 'cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
}
console.log(request);
const response = await fetch(`http://localhost:8000/chart`,request);
alert("your data has been submited");
}
Given below django code for the rest api that i'm calling
@api_view(['POST'])
def chart(request):
if request.method == 'POST':
print(request.POST)
name = request.POST['name']
day = request.POST['day']
resultset = chartModel.objects.filter(name=name,day=day)
print(len(resultset))
if (len(resultset) > 0):
return Response(status=status.HTTP_208_ALREADY_REPORTED)
serializer = ChartSerializers(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
but i'm getting error code 500 internal server error. I have come to know thats because request.POST is empty and trying call request.POST['name'] makes it MultiValueDictKeyError. but why am i not getting post request.
my API works fine i checked it with postman
I'm even using corsheader
CORS_ORIGIN_ALLOW_ALL = True
I dont know wat am i missing.. could use some help..