Search code examples
pythonionic-frameworkdjango-rest-frameworkionic4django-cors-headers

How I can enable the cors origin for function-based view in djangorest?


I've been working for simple authentication (function-based) to my mobile application. I've been wondering because the application is working when running on web ( I'm using ionic4 ), but when I try to run the application to the real device, it's not working. However, the post request for registration view is working ( both in web and real device ) and it is structured by class-based views. In my perspective, the only problem here is the cors-origin since the other views ( class-based views ) are working. Anyone know how I can setup the cors-origin of the function-based views to allow all the incoming response? Thanks!

# For clinicians
@csrf_exempt
@api_view(["POST"])
def login_as_clinician(request):

    student_number = request.data.get('student_number')
    password = request.data.get('password')
    print(secrets.token_hex())

    isExist = Clinician.objects.filter(student_number=student_number, password=password).exists()

    if isExist:
        user = Clinician.objects.get(student_number=student_number, password=password)
        data = { 'message' : 'successful', 'id' : user.id, 'student_number' : user.student_number, 'first_name' : user.first_name,
        'last_name' : user.last_name, 'middle_name' : user.middle_name, 'token' : secrets.token_hex(), 'clinic_level' : user.clinic_level }
        status = HTTP_200_OK
    else:
        data = { 'message' : 'error' }
        status = HTTP_404_NOT_FOUND

    return Response(data, status=status)

Here is the settings.py configuration

# CORS Headers
CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_METHODS = [
    'DELETE',
    'GET',
    'OPTIONS',
    'PATCH',
    'POST',
    'PUT',
]
MIDDLEWARE = [
    ...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    ...
]
INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

Solution

  • When you do the POST request, it will go with HEADERS like content-type. So you need to allow that.

    So add this after CORS_ORIGIN_ALLOW_ALL,

    CORS_ALLOW_HEADERS = ('Content-Type')
    

    Whenever you're sending something in the headers, you need to add it here. Otherwise you'll get cors errors.