1

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..

2 Answers 2

1

Use request.data instead of request.POST

Here is some more... . . . Yes, in rest framework, there are some added functionalities than what we have in django, so some parts are easier, like we do not need to have a csrf token. Though it makes sure that, that the request is made from the allowed frontend (like in cors), but still it is not that good, I can inject some javascript from the console of the same frontend (which is allowed to make requests as per cors), so still we need to make sure that somehow, we are making it harder for someone who has bad intentions.

Sign up to request clarification or add additional context in comments.

1 Comment

yeah but ... I don't think csrf token is the problem.. if that is the case, postman request should have got failed.. but request through postman is working fine even though i didn't set the csrf token..
0

Few days back I too have the similar problem but its gone when I used a forward slash after the api, You may give it a try like http://localhost:8000/chart/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.