Day 11 · 1 Hour
Full-Stack Integration
CORS, JWT auth, login flow — wire frontend and backend together end-to-end.
🔥 Real-World Hook (0–5 min)
You have a Django API. You have an HTML frontend. But when you open the HTML file and it calls the API — CORS Error. The browser refuses to let a page at file:// or localhost:3000 talk to localhost:8000.
This exact error blocked the Flipkart web team for a day. Today you wire the full stack end-to-end: CORS fixed, login flow, authenticated API calls, live data on screen.
🔒 What is CORS? (5–25 min)
⚠ CORS in 30 seconds
Browsers enforce a rule: a script on domain-a.com cannot fetch data from domain-b.com unless domain-b explicitly says "I allow this." This security rule is called CORS — Cross-Origin Resource Sharing.
Fix: install django-cors-headers and add localhost:3000 to the allowlist.
💻 Live Coding — Full-Stack Wiring (25–45 min)
# 1. Fix CORS pip install django-cors-headers # settings.py INSTALLED_APPS = [ ... "corsheaders", ... ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", # MUST be first "django.middleware.common.CommonMiddleware", ... ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:5500", # VS Code Live Server ]
# 2. Add JWT authentication pip install djangorestframework-simplejwt # settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework_simplejwt.authentication.JWTAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticatedOrReadOnly", ], } # urls.py from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns += [ path("api/token/", TokenObtainPairView.as_view()), path("api/token/refresh/", TokenRefreshView.as_view()), ]
// Frontend: login + authenticated request async function login(username, password) { const res = await fetch("/api/token/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ username, password }) }); const { access, refresh } = await res.json(); localStorage.setItem("access", access); // save token } async function fetchProtected() { const token = localStorage.getItem("access"); const res = await fetch("/api/students/", { headers: { "Authorization": `Bearer ${token}` } }); return res.json(); }
🎯 You Code It (45–55 min)
- Install
django-cors-headers, configure, restart server — confirm no more CORS error - Install
djangorestframework-simplejwt, add token URLs - Update your frontend: add a login form that calls
/api/token/and stores the JWT - Update your
addStudent()to send the Authorization header - Test: log in as superuser, add a student — confirm it saves to the Django admin
- Show: Full flow — login in browser, add student, see it in /admin
📄 Day 11 Cheat Sheet — Full-Stack Wiring
CORS Setup
| pip install django-cors-headers | Install |
| add to INSTALLED_APPS | Register |
| CorsMiddleware must be first | Critical order |
| CORS_ALLOWED_ORIGINS = [...] | Allowlist |
| CORS_ALLOW_ALL_ORIGINS = True | Dev only! |
JWT Auth
| POST /api/token/ | Get access + refresh |
| POST /api/token/refresh/ | Get new access token |
| Authorization: Bearer <token> | Header format |
| localStorage.setItem(key, val) | Store token |
| localStorage.getItem(key) | Read token |
DRF Permissions
| IsAuthenticated | Must log in |
| IsAuthenticatedOrReadOnly | Read: public, Write: auth |
| IsAdminUser | Django staff only |
| AllowAny | No restriction |
| permission_classes = [...] | Per-view override |
HTTP Status Codes
| 200 OK | Success |
| 201 Created | POST success |
| 204 No Content | DELETE success |
| 400 Bad Request | Invalid data |
| 401 Unauthorized | Not logged in |
| 404 Not Found | ID doesn't exist |