Forbidden (CSRF cookie not set.): api/endpoint/ 403

48 Views Asked by At

I'm trying to implement getting information from a form. My stack: Vue and DRF. The problem is that I implemented receiving information from the form to the server, but without a CSRF token. Then I wanted to include the decorator in APIView.

`

@method_decorator(csrf_protect, name='dispatch')
class LiteContactView(APIView):

    permission_classes = [permissions.AllowAny]

    def post(self, request):
        serializer = LiteContactSerializer(data=request.data)
        if serializer.is_valid():
            print(serializer.validated_data['phone_number'],
                  serializer.validated_data['full_name'])
            message = _('Message was sent succesfully')
            return Response({'message': message}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
`
On vue file i am using axios

`
if(!this.error.lenght) {
                

                axios
                    .post(`${this.$i18n.locale}/submit-contact/`, this.form)
                    .then(response => {
                        this.form.full_name = ''
                        this.form.phone_number = ''
                        
                        this.message = response.data.message;
                        this.$emit('submitLightForm', response.data)
                    })
                    .catch(error => {
                        console.log(error)
                    })
            }

`

My settings.py file:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'debug_toolbar.middleware.DebugToolbarMiddleware',
]


CORS_ALLOWED_ORIGINS = [
    'http://localhost:5173',
]

CSRF_TRUSTED_ORIGINS = ['http://localhost:5173']

I tried different options to get a token with a cookie but I couldn’t get it!

That's my error Forbidden (CSRF cookie not set.):

0

There are 0 best solutions below