hy2850 / NodeJS_study

Node.js 교과서 written by 조현영

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[10.7] Understanding CORS

hy2850 opened this issue · comments

API 서버 : http://localhost:8002 에서 호스팅
클라이언트 : http://localhost:4000 에서 호스팅

클라이언트 Front 내부 script에서 8002 서버로 axios request

axios.post('http://localhost:8002/v2/token', {


Network 탭

맨 위 localhost는 클라이언트가 자신의 호스팅 서버4000에 페이지 요청한 것.
아래 axios.min.js는 클라 내부 script에서 CDN에 요청한 것.
token이 Front script에서 8002번 API 서버에 요청한 req

image


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)

image

→ main req : CORS policy violation, req fails

image


2. CORS - allow all

Server allows all sources to access

const cors = require('cors');
router.use(cors());

Access-Control-Allow-Origin header added

image

CORS 적용 받고 제대로 받아진 req 모습

image


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.

// router.use(cors()); // 10-7
// Check if the client domain is registered and allow it with cors
router.use(async (req, res, next) => {
// req.header('origin') : http://localhost:4000
// host : localhost:4000
const { host } = new URL(req.header('origin'));
const domain = await Domain.findOne({
where: { host },
});
if (domain) {
// router.use(cors({ origin: host })); // ❌ Embedding middleware inside middleware - use below code
// cors({ origin: host })(req, res, next); // 🔥 req denied; mismatching origin
cors({ origin: req.header('origin') })(req, res, next);
} else {
next();
}
});


🚨 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 이므로, 완전히 일치하는 후자만 허용

image