Home > OS >  Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted
Django/React CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted

Time:11-16

I am building a web application using Django for the backend, RestApi for information transfer, and ReactJs for the frontend. When I run a POST request, in which I send data from a form, I get an error: "CSRF Failed: Origin checking failed - http://localhost:8000/ does not match any trusted origins."This means that Django recognizes the question but rejects it for some unknown reason.

ReactJs is using a proxy to work with server data. I've read already solved articles on forum such as article 1, article 2, article 3, article 4, their solutions didn't help me.

My request from ReactJs:

const item = {tittle : data.target.tittle.value, description : data.target.description.value};
axios({
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        },
     method : "post",
     url : "api/articles/",
     data : item
}).catch((e) => {console.log(e)})
       

Setting.py:

CSRF_TRUSTED_ORIGINS = [
'http://localhost:8000'
]
ALLOWED_HOSTS = [
'localhost',
]
CORS_ORIGIN_WHITELIST = [
'http://localhost:8000',
]
CORS_ORIGIN_ALLOW_ALL = True

class for processing requests in views.py:

class ArticleList(generics.ListCreateAPIView):
    def post(self, request, format=None):
        serializer = ArticleSerializer(data=request.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)
    def get(self, request, format=None):
        snippets = Articles.objects.all()
        serializer = ArticleSerializer(snippets, many=True)
        return Response(serializer.data)

CodePudding user response:

It helped me to add the authentication_classes = [] variable to the body of the class. Now my ArticleList class looks like this:

class ArticleList(generics.GenericAPIView):
    authentication_classes = []
    def post(self, request, format=None):
        serializer = ArticleSerializer(data=request.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)
    def get(self, request, format=None):
        snippets = Articles.objects.all()
        serializer = ArticleSerializer(snippets, many=True)
        return Response(serializer.data)
  • Related