CORS
CORS (Cross-Origin Resource Sharing)
A browser security mechanism that allows web pages to request resources from a different domain than the one serving the page, controlled by HTTP headers that specify which origins are permitted.
技術的詳細
CORS works through HTTP headers: Access-Control-Allow-Origin specifies permitted origins, Access-Control-Allow-Methods lists allowed HTTP methods, and Access-Control-Allow-Headers names permitted request headers. For non-simple requests (those with custom headers or methods other than GET/HEAD/POST), browsers send a preflight OPTIONS request first. Access-Control-Allow-Credentials: true enables cookie transmission. The Access-Control-Max-Age header caches preflight results. Without proper CORS headers, browsers block cross-origin fetch/XMLHttpRequest responses.
例
```javascript
// CORS: web API example
const response = await fetch('/api/resource');
const data = await response.json();
console.log(data);
```