Cross-Origin Request Blocked and Preflight executes View Django-project

In my Django and React project, I am trying to make a registration request which is failing due to a missing "Access-Control-Allow-Origin" header, resulting in a 504 error. The problem I believe I am facing is that the preflight (OPTIONS) request is already executing the View, which is causing issues with permissions for the subsequent POST request.

Jan 21 10:11:20 AllKids python3[155868]: [21/Jan/2023 09:11:20] "OPTIONS /user/register/ HTTP/1.0" 200 0
Jan 21 10:11:20 AllKids python3[155868]: in View

I am not sure why this issue is only occurring on this View, as all other views are working correctly.

Jan 21 10:21:40 AllKids python3[156001]: [21/Jan/2023 09:21:40] "POST /user/validatePassword/ HTTP/1.0" 200 613

It is worth noting that the OPTIONS request is returning a 200 status code. I would like to share the following code with you for further analysis:

   let formData = {
      password: password,
      username: username,
      email: email,
    };
    console.log(formData);
    let request = await fetch(
      `${process.env.REACT_APP_BACKEND_URL}/user/register/`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData),
      }
    );
    console.log(response, 'WTF');
    let response = await request.json();

The "WTF" line is not beeing reached since I am not getting the response... For comparison, here is an function that works perfectly fine(login):

let formData = { password: password, email: email };
let request = await fetch(
  `${process.env.REACT_APP_BACKEND_URL}/user/validatePassword/`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(formData),
  }
);
let response = await request.json();

here are my django settings:

INSTALLED_APPS = [
     ...
    "corsheaders",
]

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


CORS_ORIGIN_ALLOW_ALL = True

here is the View wich is beeing executed on the preflight request:

@api_view(["POST"])
def registerUser(request):
    print("In Function")
    body = returnContent(request)
    try:
        CustomUser.objects.get(email=body["email"])
        return Response("Email already in use!")
    except:
        if len(body["username"]) < 4:
            return Response("Username should be at least 3 characters long.")
        if body["username"][0].isdigit():
            return Response("Username should not start with a digit.")
        if len(body["password"]) < 7:
            return Response("Password must be at least 6 characters")
        randomToken = random.randrange(100000, 999999)
        user = CustomUser.objects.create_user(
            username=body["username"], email=body["email"], password=body["password"], currentVerificationToken=randomToken)
        sendEmailVerification(
            user.username, user.currentVerificationToken, user.email)
        user = CustomUserLoggedSerializer(user, many=False)
        return Response(user.data)

and this would be the login request where everything works just fine...:

@api_view(["POST"])
def validatePassword(request):
    body = returnContent(request)
    try:
        password = body["password"]
        email = body["email"]
    except:
        return Response("No Email or Password provided")

    try:
        user = CustomUser.objects.get(email=email)
    except:
        return Response("Invalid email")
    user = authenticate(request, email=email, password=password)
    if user is not None:

        if user.twoFactorVerification:
            setattr(user, "currentVerificationToken",
                    random.randrange(100000, 999999))
            user.save()
            sendEmailVerification(
                user.username, user.currentVerificationToken, user.email)
            return Response("Two-Factor Authentication Required")

        login(request, user)
        user = CustomUserLoggedSerializer(user, many=False)
        return Response(user.data)
    else:
        return Response(False)
Back to Top