Django API - CORS Error with Login (Avoiding Django REST Framework & corsheaders)

I'm new to Django and building a web API without Django REST Framework.

My Setup:

  1. Angular for frontend (compiled for production)

  2. Django backend with user login/register functionality as a First step

  3. Used collectstatic command to include Angular's compiled assets

  4. Done the setup in urls.py points to Angular's index.html for the main URL

-----------------------urls.py-------------------

from django.contrib import admin
from django.urls import include, path
from django.views.generic import TemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/auth', include('user_auth.urls')),
    path('', TemplateView.as_view(template_name='index.html')),
    path('<path:path>', TemplateView.as_view(template_name='index.html')),
]


-----------------------settings.py-------------------

STATIC_URL = 'static/'
STATICFILES_DIRS = [BASE_DIR / 'frontend/dist/frontend/browser']
STATIC_ROOT = BASE_DIR / 'static'

CORS_ALLOWED_ORIGINS = [
    "http://localhost:4200",  # Angular dev server
    "http://127.0.0.1:4200",
    "http://localhost:8000",  # Django server
    "http://127.0.0.1:8000",
]

CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000', 'http://127.0.0.1:8000'
)
CORS_ALLOW_ALL_ORIGINS = True

CORS_ALLOW_HEADERS = [
    'content-type',
    'X-CSRFToken',
    'authorization',
    'Access-Control-Allow-Origin',
    'Access-Control-Allow-Headers'
]

Issue:

I'm encountering a CORS error when making a login request to http://127.0.0.1:8000/api/auth/login.

Attempts:

I tried using the corsheaders package to resolve the issue with CORS and CORS issue has been resolved but then faced a CSRF token issue when make a post request to the http://127.0.0.1:8000/api/auth/login.. I understand by using the csrf_exempt decorator i can resolve the issue,

Question:

  1. Is my approach of building a custom API without external packages feasible and correct?

Thank you!

Back to Top