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:
Angular for frontend (compiled for production)
Django backend with user login/register functionality as a First step
Used
collectstatic
command to include Angular's compiled assetsDone 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:
- Is my approach of building a custom API without external packages feasible and correct?
Thank you!