CORS policy: The value of the ‘Access-Control-Allow-Origin’ header in the response must not be the wildcard ‘*’ when credentials flag is true

CORS hiba: ne használj '*' -ot, ha a fetch credentials: 'include'-t állítasz, helyette pontos domain-t adj meg.

CORS wildcard credentials

Hibaüzenet

CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when credentials flag is true

Hibás kód

// fetch mód:
fetch('/api', { credentials: 'include' });

Javított kód

// Szerver oldalon:
// res.setHeader('Access-Control-Allow-Origin', 'https://teoldalad.hu');
fetch('/api', { credentials: 'include' });

Magyarázat

CORS wildcard credentials hiba akkor jelenik meg, amikor egy fetch kérést a böngészővel cookies-szal együtt (`credentials: ‘include’`) küldesz, de a szerver az Access-Control-Allow-Origin: * fejlécet használja. A szabvány tiltja a wildcard ‘*’ használatát hitelesített kérések esetén. A megoldás, hogy explicit megadod a domain nevet: res.setHeader('Access-Control-Allow-Origin', 'https://teoldalad.hu'), így a böngésző elfogadja a cookie-kat és a kérést.

További információ: MDN – CORS Credentials