A developer uses 'fetch()' in a browser and notices it fails with a CORS error when calling their own API. The API is at 'https://api.example.com' and the frontend is at 'https://app.example.com'. Why does this count as cross-origin?
- A.It does not count as cross-origin since both share the 'example.com' root domain
- B.The Same-Origin Policy defines origin as scheme + hostname + port. 'api.example.com' and 'app.example.com' have different hostnames, making them different origins regardless of sharing a common root domain
- C.This counts as cross-origin only if the ports differ
- D.Cross-origin only applies when the scheme (http vs https) differs
Why B is correct
The Same-Origin Policy considers scheme, hostname, and port together as the origin. 'https://api.example.com' and 'https://app.example.com' differ in hostname, making them cross-origin. Subdomains are separate origins under SOP. To allow cross-origin requests between them, the API server must include appropriate CORS headers. Some older APIs incorrectly assumed shared TLDs meant same-origin.
Know someone studying for Web App Fundamentals? Send them this one.