🟑 CORS(Cross-Origin Resource Sharing)λž€?

<aside> πŸ’‘

λ‹€λ₯Έ 좜처(Origin) κ°„μ˜ μžμ› 곡유λ₯Ό λΈŒλΌμš°μ €μ—μ„œ ν—ˆμš©ν•˜λ„λ‘ μ •μ˜ν•œ λ³΄μ•ˆ μ •μ±…

즉, λΈŒλΌμš°μ €κ°€ λ³΄μ•ˆμƒμ˜ 이유둜 μ™ΈλΆ€ λ„λ©”μΈμ˜ λ¦¬μ†ŒμŠ€ 접근을 기본적으둜 λ§‰λŠ” 것을 μ œμ–΄ν•˜λŠ” 방법

</aside>


좜처(Origin)λž€?

μΆœμ²˜λŠ” λ‹€μŒ 3κ°€μ§€λ‘œ κ΅¬μ„±λ©λ‹ˆλ‹€:

ꡬ성 μš”μ†Œ μ˜ˆμ‹œ
μŠ€ν‚΄ http, https
호슀트 www.example.com
포트 :3000, :8080

이 μ…‹ 쀑 ν•˜λ‚˜λΌλ„ λ‹€λ₯΄λ©΄ **λ‹€λ₯Έ 좜처(Other Origin)**간주됨.

πŸ” μ˜ˆμ‹œ

μš”μ²­ URL 같은 μΆœμ²˜μΈκ°€?
http://localhost:3000 β†’ http://localhost:3000 βœ… 같은 좜처
http://localhost:3000 β†’ http://localhost:4000 ❌ λ‹€λ₯Έ 포트
http://example.com β†’ https://example.com ❌ λ‹€λ₯Έ μŠ€ν‚΄
http://example.com β†’ http://api.example.com ❌ λ‹€λ₯Έ 호슀트

🚫 CORS μ—λŸ¬ μ˜ˆμ‹œ

Access to fetch at '<http://api.example.com/data>' from origin '<http://localhost:3000>'
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present...

ν•΄κ²° 방법

1. μ„œλ²„μ—μ„œ CORS ν—ˆμš© 헀더 μΆ”κ°€

μ„œλ²„ 응닡 헀더에 μ•„λž˜μ™€ 같은 섀정을 μΆ”κ°€ν•˜λ©΄ 해결됨:

Access-Control-Allow-Origin: <http://localhost:3000>
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization

Spring Bootμ—μ„œ CORS μ„€μ • 방법

방법 1: Controller λ‹¨μœ„ μ„€μ •