CORS (Cross-Origin Resource Sharing) is a browser security policy that prevents web pages from making requests to other domains without permission. Protects users from data theft. 🛡️
// ❌ CORS Error:
// Site example.com tries to request data from api.other.com
fetch('https://api.other.com/data')
.then(response => response.json())
.catch(error => console.log('CORS error!')); // Blocked by browser
// ✅ Solution — server must allow requestCORS is like a security guard at a building entrance who checks if you’re allowed to enter and take things from there. Without permission — no way! 🚫
Browser considers requests “same-origin” if they match:
// ✅ Same origin:
// https://example.com/page1
// https://example.com/page2
// ❌ Cross-origin:
// https://example.com ❌ https://api.com
// http://example.com ❌ https://example.com
// https://example.com ❌ https://example.com:8080// ❌ Blocked if server doesn't allow:
fetch('https://api.other.com/users')
.then(response => response.json())
.catch(error => {
console.log('CORS blocks request!'); // Error in console
});// ❌ Problem — user protection:
// Malicious site evil.com shouldn't
// steal data from bank.com!
// CORS requires explicit server permission// For complex requests browser first sends OPTIONS:
// 1. Browser: OPTIONS /api/data (preflight request)
// 2. Server: "Allowed!" (Access-Control-Allow-Origin: *)
// 3. Browser: GET /api/data (real request)
// 4. Server: Sends data// Server must send headers:
Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization// ✅ Server allows:
// Access-Control-Allow-Origin: * (all domains)
// Or specifically:
// Access-Control-Allow-Origin: https://example.com// ✅ For development:
// 1. Use proxy server
// 2. Disable CORS in browser (only for testing!)
// 3. Use browser extensions// ❌ Mistake — think server returned error:
fetch('https://api.other.com/data')
.catch(error => {
// It's CORS blocking, not server!
});
// ✅ Correct — check Network tab in DevTools// ❌ Bad — allow everyone:
// Access-Control-Allow-Origin: *
// For sensitive data!
// ✅ Better — restrict to specific domainsUnderstanding CORS helps solve API request issues and create secure web applications! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪