Skip to lesson

Why the browser blocks cross-origin calls

A ShopLite page on port 3000 calls the ShopLite API on port 8080, on the same laptop. Chrome blocks the answer, yet the same call works in curl. Why does the browser say no?

Origin: scheme, host and port

An origin is the first part of a URL: its scheme (http or https), its host and its port. Two URLs share an origin only when all three match exactly; the path, the query string and the #fragment never count.

The program below prints the origin of six page and API URL pairs, then says whether each pair is the same origin or why not.

Example 1 · Same origin or not? Work it out in Java

OriginDemo.javaJava
import java.net.URI;
public class OriginDemo {
    static String url(String scheme, String hostAndPort, String path) {        return scheme + "://" + hostAndPort + path;    }
    static String origin(String url) {        URI uri = URI.create(url);        String scheme = uri.getScheme().toLowerCase();        String host = uri.getHost().toLowerCase();        int port = uri.getPort() != -1 ? uri.getPort() : defaultPort(scheme);        boolean defaultPort = port == defaultPort(scheme);        return scheme + "://" + host + (defaultPort ? "" : ":" + port);    }
    static int defaultPort(String scheme) {        return scheme.equals("https") ? 443 : 80;    }
    static String why(String page, String api) {        URI a = URI.create(page);        URI b = URI.create(api);        if (!a.getScheme().equalsIgnoreCase(b.getScheme())) {            return "cross-origin: scheme differs";        }        if (!a.getHost().equalsIgnoreCase(b.getHost())) {            return "cross-origin: host differs";        }        if (!origin(page).equals(origin(api))) {            return "cross-origin: port differs";        }        return "same origin";    }
    static void check(String page, String api) {        System.out.println(origin(page) + "  ->  " + origin(api) + "   " + why(page, api));    }
    public static void main(String[] args) {        check(url("http", "localhost:3000", "/index.html"), url("http", "localhost:8080", "/api/v1/products"));        check(url("http", "localhost:8080", "/swagger-ui.html"), url("http", "localhost:8080", "/api/v1/products"));        check(url("https", "shoplite.example", "/"), url("https", "shoplite.example:443", "/api/v1/products?page=0"));        check(url("https", "shoplite.example", "/cart"), url("http", "shoplite.example", "/api/v1/products"));        check(url("https", "shoplite.example", "/cart"), url("https", "api.shoplite.example", "/api/v1/products"));        check(url("http", "localhost:3000", "/"), url("http", "127.0.0.1:3000", "/api/v1/products"));    }}
Output
http://localhost:3000  ->  http://localhost:8080   cross-origin: port differs
http://localhost:8080  ->  http://localhost:8080   same origin
https://shoplite.example  ->  https://shoplite.example   same origin
https://shoplite.example  ->  http://shoplite.example   cross-origin: scheme differs
https://shoplite.example  ->  https://api.shoplite.example   cross-origin: host differs
http://localhost:3000  ->  http://127.0.0.1:3000   cross-origin: host differs

What this code does

  • url() joins scheme, host and port the way you read them in the address bar. origin() keeps only those three parts, fills in the default port (80 or 443) and leaves it out when it is the default, the way browsers write an origin. Paths such as /api/v1/products?page=0 disappear.
  • Line 3 shows that :443 written out is still the same origin as no port on https. The last two lines are the two cases students trip on: a sub-domain and 127.0.0.1 are different hosts.

When a port is not written, the scheme's default is used: 80 for http and 443 for https. So https://shoplite.example and https://shoplite.example:443 match. Host names ignore case, but localhost and 127.0.0.1 are different hosts, and a sub-domain such as api. is another host too.

The usual student setup is already cross-origin: the frontend's dev server runs on port 3000 and Spring Boot on port 8080. Same computer, same localhost, different port, so a different origin.

Predict the output

Same origin or not?

A page on the first URL calls the second URL. Pick what the browser decides.

Round 1 of 3

Only the path differs.

page: http://localhost:3000/cart
api: http://localhost:3000/api/v1/products
Interview angle: "Is api.shoplite.example the same origin as shoplite.example?" No. A sub-domain is a different host, so it is a different origin.

The same-origin policy: what it protects

The same-origin policy is a browser rule: JavaScript on a page may read responses only from its own origin. A request to another origin is cross-origin: the browser may send it, but the page cannot read the answer.

The page below asks the ShopLite API on port 8080 for a product. The API has no CORS settings yet, so watch what Chrome does with the answer.

Example 2 · A page on port 3000 calls the ShopLite API on port 8080

Runs in: a page served on http://localhost:3000 and the ShopLite API (no CORS yet) on http://localhost:8080, in Chrome

JAVASCRIPT
// shop.js, loaded by the page http://localhost:3000/index.htmlasync function loadProduct() {  try {    const response = await fetch('http://localhost:8080/api/v1/products/1');    const product = await response.json();    console.log('Product:', product.name, product.price);  } catch (error) {    console.log('fetch failed ->', error.name + ': ' + error.message);  }}loadProduct();
Browser console (Chrome)
Access to fetch at 'http://localhost:8080/api/v1/products/1' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Failed to load resource: net::ERR_FAILED
fetch failed -> TypeError: Failed to fetch

What this code does

  • The page and the API are on the same computer, but the ports differ, so the call is cross-origin. The API has no CORS settings yet, so its response has no Access-Control-Allow-Origin header.
  • The browser blocked the response and wrote the reason to the console. The page's own code got only TypeError: Failed to fetch, so the catch block ran and Product: was never printed.

The rule exists because the browser adds your cookies to every request it sends to a site, whoever asked for it. Without the rule, a page you open from a random link could call your college ERP or your bank in the background, with your cookies, and read your marks or balance. The policy also shields machines that only your browser can reach, such as a hostel router's admin page at http://192.168.1.1.

What the policy does and does not block:

  • Allowed without asking: loading images, scripts and stylesheets from other origins, and submitting a form to another origin.
  • Blocked unless the server allows it: JavaScript reading a cross-origin response made with fetch or XMLHttpRequest.
  • Never shared: cookies, localStorage and the page content of another origin.
The same-origin policy protects the user of the browser. It does not protect your API from other programs; the next section shows why.

The browser enforces CORS, not the server

CORS (Cross-Origin Resource Sharing) is how a server tells the browser, with response headers, which other origins may read its responses. The browser enforces it; the server only sends the headers.

Now the same call with curl, which is not a browser. It sends the same Origin header the page sent.

A page on http://localhost:3000 asks the ShopLite API on http://localhost:8080 for a product. The browser sends the request with an Origin header. The API answers with the body, with or without Access-Control-Allow-Origin.

Example 3 · The same call with curl works

Runs in: a terminal, with the ShopLite API (no CORS yet) running on port 8080

Terminal
curl -i http://localhost:8080/api/v1/products/1 -H "Origin: http://localhost:3000"
Sample output (Spring Security's Cache-Control, Pragma, Expires and X- headers left out; your Date differs)
HTTP/1.1 200 
Content-Type: application/json
Content-Length: 135
Date: Fri, 16 Oct 2026 08:05:09 GMT

{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}

What this code does

  • curl sends the same Origin header the browser sent, and the API answers 200 with the full product. The server never refused anything: the request reached the controller and the database.
  • There is no Access-Control-Allow-Origin line in the response. That single missing header is why Chrome hid this exact body from the page in Example 2.

The server never blocks anything for CORS: it runs the controller and sends the response. The browser then looks for Access-Control-Allow-Origin in that response and throws the response away when the header is missing or names another origin. So curl, Postman, Java's HttpClient and mobile apps never meet CORS errors. When a call works in Postman but fails in the browser, the CORS setup is the problem, not the controller.

CORS controls who can read, not who can send. A cross-origin POST that the browser counts as simple reaches the server and runs, even though the page never sees the answer. Protection against forged writes needs other tools, such as a token in a header instead of a cookie.

Order of execution

Order a cross-origin fetch

Put the steps of one cross-origin fetch in the order they happen.

Debugging habit: reproduce the call with curl -i and an -H "Origin: ..." header. If curl gets the data but no Access-Control-Allow-Origin, the fix is on the server's CORS settings, not in the controller.

Reading a CORS error in the browser console

A CORS error is the message Chrome writes to the developer console when it blocks a cross-origin response. The code of the page itself sees only a vague TypeError: Failed to fetch.

Three real Chrome messages follow, with what each one means.

Example 4 · Three real CORS errors and what each one means

Text
(1) Access to fetch at 'http://localhost:8080/api/v1/products/1' from origin 'http://localhost:3000'    has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the    requested resource.(2) Access to fetch at 'http://localhost:8080/api/v1/me/orders' from origin 'http://localhost:3000'    has been blocked by CORS policy: Response to preflight request doesn't pass access control    check: No 'Access-Control-Allow-Origin' header is present on the requested resource.(3) Access to fetch at 'http://localhost:8080/api/v1/auth/login' from origin 'http://localhost:3000'    has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value    'http://127.0.0.1:3000' that is not equal to the supplied origin. Have the server send the    header with a valid value.
What to fix
(1) The API answered, but without Access-Control-Allow-Origin: CORS is not set up at all.
(2) The browser asked first (a preflight, next lesson) and the answer had no CORS headers.
(3) CORS is set up, but for a different origin: 127.0.0.1 and localhost are different hosts.

What this code does

  • All three are real Chrome messages from the test runs for this module (API port shown as 8080). The first part (URL and origin) tells you which call failed; the part after blocked by CORS policy: tells you which header to look at.
  • Messages (1) and (2) mean the server sent no CORS headers at all. Message (3) means the server did send them, so CORS is configured, but with the wrong origin.

Chrome's messages share one shape: Access to fetch at '<URL>' from origin '<page origin>' has been blocked by CORS policy: and then the reason. Read the URL, the page origin and the reason; the reason names the exact header that was missing or wrong. The vague error for the page is on purpose, so a page cannot probe other sites. The full reason is written only to the console (F12, Console tab). In the Network tab the request shows as failed with CORS error, even when the server sent 200 OK.

The three reasons you will meet most:

  • No 'Access-Control-Allow-Origin' header is present: CORS is not set up for that URL, or the security chain answered before CORS could run.
  • Response to preflight request doesn't pass access control check: the OPTIONS request that the browser sent first got the wrong answer.
  • has a value '...' that is not equal to the supplied origin: CORS is set up, but for a different origin (a port, host or scheme typo).

Fix the error

Fix the allowed origin

The page runs on http://localhost:3000. Pick the replacement for the highlighted line.

Round 1 of 2

The page is on localhost, but the allowed origin names 127.0.0.1.

CorsConfiguration api = new CorsConfiguration();
api.setAllowedOrigins(List.of("http://127.0.0.1:3000"));
api.setAllowedMethods(List.of("GET", "POST"));

Error

has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value
'http://127.0.0.1:3000' that is not equal to the supplied origin.

Access-Control-Allow-Origin and the other CORS headers

Access-Control-Allow-Origin is the response header that names the one origin, or *, that may read the response. The browser compares it letter by letter with the page's origin.

The same curl call against the ShopLite API, now with CORS set up for the page on port 3000. Look for the new headers in the answer.

Example 5 · The ShopLite API with CORS set up for localhost:3000

Runs in: a terminal, with the ShopLite API (dev profile, CORS configured) running on port 8080

Terminal
curl -i http://localhost:8080/api/v1/products/1 -H "Origin: http://localhost:3000"
Sample output (Spring Security's Cache-Control, Pragma, Expires and X- headers left out; your Date differs)
HTTP/1.1 200 
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Expose-Headers: Location
Content-Type: application/json
Content-Length: 135
Date: Fri, 16 Oct 2026 08:05:12 GMT

{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","categoryId":2,"categoryName":"Mobiles","price":17999.00,"stock":40,"isActive":true}

What this code does

  • The body is the same as in Example 3. What changed is four headers: Access-Control-Allow-Origin names the page's origin exactly, Access-Control-Expose-Headers: Location lets JavaScript read Location on created items, and the Vary lines keep caches honest.
  • With this header, the page from Example 2 prints Product: Redmi Note 13 5G 17999. The Configuring CORS lesson in this module shows the Spring Security code that adds these headers.

The browser sends the page's origin in the Origin request header, and a CORS-aware server answers with these headers:

  • Access-Control-Allow-Origin: the origin allowed to read the response. Access-Control-Allow-Credentials: true: cookies may be sent and the response read with them.
  • Access-Control-Expose-Headers: extra response headers JavaScript may read, such as Location (by default it sees only a few, like Content-Type).
  • Access-Control-Allow-Methods, Access-Control-Allow-Headers, Access-Control-Max-Age: the answers to a preflight, covered in the next lesson.

Spring also adds Vary: Origin. The line tells caches (a CDN, a proxy, the browser cache) that the answer depends on the Origin header, so a response made for one site is never reused for another.

Next step

Check your understanding

12 quick questions