[10.7] Understanding CORS
hy2850 opened this issue · comments
API 서버 : http://localhost:8002 에서 호스팅
클라이언트 : http://localhost:4000 에서 호스팅
클라이언트 Front 내부 script에서 8002 서버로 axios request
Network 탭
맨 위 localhost는 클라이언트가 자신의 호스팅 서버4000에 페이지 요청한 것.
아래 axios.min.js는 클라 내부 script에서 CDN에 요청한 것.
token이 Front script에서 8002번 API 서버에 요청한 req
Request/Response headers per situation
1. No CORS setting
(Chrome default CORS policy) same origin policy (SOP) applies
preflight req : origin differs from host (server)
→ main req : CORS policy violation, req fails
2. CORS - allow all
Server allows all sources to access
const cors = require('cors');
router.use(cors());
Access-Control-Allow-Origin
header added
CORS 적용 받고 제대로 받아진 req 모습
3. CORS - allow specific domains registered on DB
Check if client sending request has its domain registered.
Add the domain with cors if it does.
NodeJS_study/Ch 10. 웹 API 서버 만들기/nodebird-api/routes/v2.js
Lines 12 to 30 in 7320e9e
🚨 Protocol (http, https) 까지 완벽히 같아야 같은 Origin - Ref
// req.header('origin') : http://localhost:4000
// host : localhost:4000
cors({ origin: host })(req, res, next); // ❌ Access-Control-Allow-Origin: localhost:4000
cors({ origin: req.header('origin') })(req, res, next); // ✔️ Access-Control-Allow-Origin: http://localhost:4000
Request header Origin: http://localhost:4000
이므로, 완전히 일치하는 후자만 허용