简体   繁体   中英

Ajax post getting 403 forbidden error with Django Rest Framework

There are loads of similar questions but each seems to deal with the problem under different scenarios, or the perscribed solution doesn't seem to resolve my issue. Basically, Why am I getting this 403 Forbidden Error?

POST http://127.0.0.1:8000/api/hello-viewset/ 403 (Forbidden)

The url is a Django Rest Framework (DRF) endpoint that I can access from the browser and make POSTs using the DRF gui just fine. The trouble is when I try to POST using Ajax from my javascript file. Note, that I am passing the CSRFToken (as advised here ):

$.ajax({
    type: "POST",
    url: '/api/hello-viewset/',
    csrfmiddlewaretoken: window.CSRF_TOKEN, // yes, this variable is set successfully
    data: {first_name: username},
    success: function(data){
        console.log( 'success, server says '+data);
    }
});

The /api/hello-viewset/ url is just a simplified test view that looks like this:

class HelloViewSet(viewsets.ViewSet):

    serializer_class = serializers.HelloSerializer

    def post(self, request):
        serializer = serializers.HelloSerializer(data=request.data)

        if serializer.is_valid():
            first_name = serializer.data.get('first_name')
            message = 'Hello {0}'.format(first_name)
            return Response({'message': message})
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Thanks in advance for your help?

csrfmiddlewaretoken: window.CSRF_TOKEN is not set correctly. It should be added to data, ie:

$.ajax({
    type: "POST",
    url: '/api/hello-viewset/',
    data: {
        first_name: username,
        csrfmiddlewaretoken: window.CSRF_TOKEN
    },
    success: function(data){
        console.log( 'success, server says '+data);
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM