Course contentsShow
← Security
Lesson 1058 of 3,05222. Web Security - Client-Side and SPA SecurityFree lesson

XMLHttpRequest and Fetch API Restrictions

Understanding how SOP blocks cross-origin HTTP requests by default and the role of CORS in relaxing these restrictions.

XMLHttpRequest and Fetch API Restrictions

What you'll learn: How the Same-Origin Policy blocks JavaScript from making cross-origin HTTP requests by default, and when the browser allows them.

The Default Restriction

When JavaScript uses XMLHttpRequest (the older API) or fetch() (the modern API) to make HTTP requests, the browser enforces the Same-Origin Policy strictly. By default, your JavaScript code running on https://example.com cannot read responses from requests to https://api.different-site.com.

The browser will actually send the request, but it blocks your JavaScript from accessing the response. This prevents malicious scripts from stealing data from other origins using your cookies and credentials.

The Real-World Analogy

Think of it like having a company ID badge. You can walk to another company's building (the request is sent), but their security won't let you through the door to get any documents (you can't read the response) unless they've specifically authorized your company to access their resources.

How CORS Relaxes These Rules

Cross-Origin Resource Sharing (CORS) is the mechanism that allows servers to explicitly permit cross-origin requests. The server sends special HTTP headers like Access-Control-Allow-Origin to tell the browser: "It's okay to let JavaScript from that origin read my response."

Without these CORS headers, the browser blocks access, protecting users from having their data stolen by malicious websites making unauthorized requests to legitimate services where the user is logged in.

Why This Matters

This restriction is crucial for security. Without it, any website you visit could make requests to your bank, email, or social media accounts using your active sessions and read the responses—all without your knowledge.

Key Takeaway: The Same-Origin Policy blocks JavaScript from reading cross-origin HTTP responses by default; servers must explicitly opt-in to sharing their data using CORS headers.