Blocked by CORS Is Not Your Code’s Fault

The same URL works in curl but your fetch gets a red line — because the browser blocks the response, it doesn’t fail the request. What that means, and the two honest fixes.

7 min read

Argued into existence in the Writing Room7 messages · 1 mind changedBlocked by CORS Is Not Your Code’s Fault

You have edited your fetch three times now. (fetch is the browser's built-in way for your page's JavaScript to request data from a URL.) You added a header. You tried mode: 'no-cors'. You swapped the URL. The red line in the console (the browser's error panel: right-click the page, choose Inspect, then the Console tab) hasn't moved, and the same URL works fine when you paste it into the address bar or run it in curl, a command-line tool that requests a URL and prints the answer.

So you're certain the bug is in your code. It isn't. Here is the one idea that ends the hour-long loop: the browser got your answer and then refused to show it to your page, and only the other server can change that. By the end you'll know how to tell which of two fixes you need, and you'll have built both.

What you need

Node 22 (a program that runs JavaScript outside the browser) and a new empty folder to save files in. I ran everything on Node 22, where global fetch is built in. No install, no package.json. You'll use up to three terminals, the text windows where you type commands: open each one in that folder.

What the error actually says

You've probably pasted something like this into a search box: "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource". Or its quieter cousin, "TypeError: Failed to fetch".

Two words in that line. CORS is Cross-Origin Resource Sharing: the browser's rule about which other sites your page is allowed to read answers from. A header is a line of information a server (a program that answers requests) clips to the top of its response, separate from the body — think of the label on a parcel versus what's inside. The whole error is about one missing label.

Read that first line again. It doesn't say your request failed. It says your page was blocked. Those are different events.

Here's the mental model. Your browser sends the request. The other server answers, and the answer arrives inside the browser. Then the browser looks for a permission slip on it, and if the slip is missing, it refuses to hand the answer to your JavaScript. Nothing broke in transit; the response was turned away at the door.

That's why curl "works". Curl isn't a page, so there's nobody to be refused. The same goes for Postman (an app for testing requests) and the address bar.

Build a fake API that has no permission slip

An API is a server that hands out data for other programs to use. Let's prove the point with a pretend one in about six lines. Save this as api.mjs:

// api.mjs - pretend this is somebody else's server
import http from 'node:http';
http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ joke: 'It works on my machine.' }));
}).listen(4000);

Start it in one terminal with node api.mjs. In a second terminal, ask it for the joke and show the headers too:

curl -si localhost:4000

Here's what came back, trimmed:

HTTP/1.1 200 OK
Content-Type: application/json

{"joke":"It works on my machine."}

A 200 (the code for "OK, here's your answer"), a body, and no Access-Control-Allow-Origin line anywhere. That is a perfectly healthy response with no permission slip. Curl doesn't care. A browser page asking from a different origin would care a lot.

What an "origin" is

An origin is three things glued together: the scheme (http or https), the host (localhost, example.com), and the port (5173, 4000). Localhost means your own computer, and a port is a numbered door on a computer that a program listens at.

Change any one and it's a different origin. I checked with the URL object in Node, which has an origin property you can read yourself:

const a = new URL('http://localhost:5173/index.html').origin;
const b = new URL('http://localhost:4000').origin;
console.log(a === b); // false: same host, different port

const c = new URL('https://a.com').origin;
const d = new URL('http://a.com').origin;
console.log(c === d); // false: same host, different scheme

Both print false. So your page on localhost:5173 and an API on localhost:4000 are strangers, even though both say "localhost". Whenever your page asks a stranger for data, the browser wants that stranger to say, in a header, "yes, that page may read my answer".

Why none of your three edits could work

The permission lives on the response, and the response comes from a server you don't control. Your fetch only controls the request.

Adding request headers can't forge a response header. Swapping the URL just asks a different stranger. And mode: 'no-cors', as I understand it, doesn't unlock anything. It tells the browser to send the request and then hand your code an opaque, unreadable response, so you swap an error for an empty box.

If an AI assistant told you to put a wildcard in a header, or to switch on no-cors, it was patching the symptom. The wildcard only makes sense in one of the two situations below, and which one you're in depends on one question: do you own the API?

Fix 1: you own it, so add one line on the response

It's your server, so the permission can come from you: one line in writeHead, the call that sets the status and headers of a response. Here is api.mjs again, with the single line added. Stop the old one, save, and run node api.mjs again:

// api.mjs - now it's YOUR server, so you add the slip
import http from 'node:http';
http.createServer((req, res) => {
  res.writeHead(200, {
    'Content-Type': 'application/json',
    'Access-Control-Allow-Origin': 'http://localhost:5173', // the one new line
  });
  res.end(JSON.stringify({ joke: 'It works on my machine.' }));
}).listen(4000);

Curl again. I ran exactly that:

HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: http://localhost:5173

There's the slip. Name the specific origin, the way I did. A wildcard, 'Access-Control-Allow-Origin' set to '*', says "any website may read this"; for a toy that's fine, but I'd call it shipped ugly, not a best practice. That's the whole fix when the server is yours.

Fix 2: you don't own it, so put a server in the middle

It's a weather service, a jokes endpoint, someone's AI model API. You can't add a header to a server that isn't yours, so you put a server of your own in the middle. That's a proxy, a go-between that passes requests along and hands the answers back.

It works because a server asking another server isn't a browser page. There's no origin check to fail. Your little server fetches the data happily, then answers your page with the permission slip attached.

  1. Save this as proxy.mjs next to api.mjs:
// proxy.mjs - fetch for your page, with a permission slip attached
import http from 'node:http';
const TARGET = 'http://localhost:4000';   // the API you don't own
const ME = 'http://localhost:5173';       // your page's origin
http.createServer(async (req, res) => {
  try {
    const upstream = await fetch(TARGET + req.url);
    res.writeHead(upstream.status, {
      'Content-Type': upstream.headers.get('content-type') ?? 'text/plain',
      'Access-Control-Allow-Origin': ME,    // the permission slip
    });
    res.end(Buffer.from(await upstream.arrayBuffer()));
  } catch {
    res.writeHead(502, { 'Access-Control-Allow-Origin': ME });
    res.end('The proxy could not reach the API.');
  }
}).listen(8787, () => console.log('proxy on 8787'));
  1. Keep the fake API running and start the proxy in a third terminal with node proxy.mjs. It's under twenty lines; the try/catch (code that attempts something and, if it errors, runs a fallback instead of crashing) is the only part you might not have reached for yourself.
  2. Ask the proxy for the same joke:
curl -si localhost:8787

Here's what I got:

HTTP/1.1 200 OK
Content-Type: application/json
Access-Control-Allow-Origin: http://localhost:5173

{"joke":"It works on my machine."}

The slip is there. I sent no Origin header this time: the proxy attaches the slip to every response, because ME is hardcoded in it (typed straight into the code). Curl can show you the slip is present, but only a browser compares that value against the origin the page is really running from. So the last step is yours.

Where it goes wrong: a 502 from the proxy

If asking the proxy prints a red line instead of the joke, check the API first. Stop the fake API, leave the proxy running, and ask again:

curl -si localhost:8787
HTTP/1.1 502 Bad Gateway
Access-Control-Allow-Origin: http://localhost:5173

The proxy could not reach the API.

That 502 is the proxy saying it couldn't reach the API, which is a different problem from CORS. The try/catch turns a bare crash into that one honest line, so you know to restart api.mjs rather than edit your page again.

Point your page at the proxy

In your page, change the one URL and nothing else, then reload it:

const res = await fetch('http://localhost:8787');
const data = await res.json();
console.log(data.joke);

You'll know it worked when the console prints the joke instead of the red line.

If it doesn't, a common culprit is a mismatched origin. If your page is served from a different port than the one in the ME line, change ME to match, then restart the proxy. Read your page's port from the address bar: it's the number after "localhost:" (a file you just double-clicked has no port at all, which is its own reason the origins never match). That's a thirty-second fix, not a mystery.

Recap

  • CORS blocks your page from reading a response; the request itself usually worked.
  • The permission is a header on the response, so your fetch can't supply it. An origin is scheme, host and port, and changing any one makes a stranger.
  • You own the API: add 'Access-Control-Allow-Origin' with the specific origin.
  • You don't: build a proxy of your own, but keep it for your machine while you build, since a public one that forwards anything anywhere is an open door. Never put a secret API key in the page, since anything in the page is readable; the proxy is the place to keep it.

Do it tonight: make api.mjs, run the curl, watch the response arrive with no permission slip, then add the proxy and watch the header appear. Ten minutes, and that red line will never scare you again.

Blocked by CORS Is Not Your Code’s Fault | Vibecodes