Frontend Development · Tutorial 9 of 9
Fix CORS Errors When Calling an API from JavaScript
By the FUTEAC Team · 14 November 2026 · 9 min read · Beginner
In short
The exact error: Access to fetch at 'http://127.0.0.1:8002/api/plain' from origin 'http://127.0.0.1:8001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. The cause: your JavaScript called an API on a different origin, and the API's response carried no Access-Control-Allow-Origin header. The browser received the response and refused to hand it to your script. The fix: add that header on the server, not in your JavaScript. Nothing you change in fetch() alone will fix it.
- CORS is a browser rule, not a server error. The API answered fine. The browser blocked your script from reading the answer because the API did not say your origin was allowed.
- The address bar is not a test. Typing an API URL into the address bar is a plain navigation, not a cross-origin script call, so it never triggers CORS. A working address bar proves nothing about your
fetch()call. - The fix lives on the server. One header,
Access-Control-Allow-Origin, with your site's origin as its value, is the whole fix for a simple GET request. - POST requests with JSON ask first. A
fetch()POST with a JSON body sends a preflight OPTIONS request before the real one, and the server must answer that too. - Credentials change the rule. If your request sends cookies with
credentials: "include", a wildcard*header is refused. The server must name your exact origin and sendAccess-Control-Allow-Credentials: true. - This tutorial feeds the JavaScript Essentials course (/course/javascript-essentials) and the Fetch & AJAX (/skill/fetch-and-ajax) and REST APIs (/skill/rest-apis) skills.
Before you start
What is an origin, and when does CORS apply?
An origin is the combination of protocol, domain and port. http://localhost:3000 and http://localhost:8002 are two different origins because the ports differ, even though both are on your own machine. https://futeac.com and http://futeac.com are two different origins because the protocol differs.
CORS, Cross-Origin Resource Sharing, is the browser's rule for one origin's JavaScript reading another origin's response. It applies only to script calls like fetch(), never to plain navigation. The rule is simple: the server must opt in by sending an Access-Control-Allow-Origin header naming the caller's origin. Without that header, the browser blocks the response from reaching your script.
Think of it like a letter with a return address the recipient does not recognise. The post arrived, but the doorman will not hand it over without the sender's name on the approved list. The letter itself was never the problem.
How do you read the error properly?
Open the browser console and read the whole message. It names three things you need: the API URL, your page's origin, and the exact reason. Here is the real message from this tutorial's test run, a page on port 8001 calling an API on port 8002:
Access to fetch at 'http://127.0.0.1:8002/api/plain' from origin 'http://127.0.0.1:8001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.And in your JavaScript, the fetch() promise rejects with a deliberately vague error:
TypeError: Failed to fetchThat vagueness is on purpose. The browser will not tell your script details about another origin's response, so fetch() only says it failed. The console message is where the truth lives, which is why the first step of every CORS fix is opening the console, not changing code.
Why does the API work in the address bar?
This is the question that wastes the most beginner time, so answer it once and move on. Typing http://127.0.0.1:8002/api/plain into the address bar is a navigation. The browser loads the response as a page and shows you the JSON. No script from another origin is involved, so CORS never applies.
Your fetch() call is different. It is a script on origin A asking to read origin B's data, and that is exactly the situation CORS exists to control. So a working address bar tells you the API is up and the URL is right. It tells you nothing about whether your page is allowed to read it. When the console says the header is missing, believe the console.
The fix, step by step: add the header on the server
The fix is one header on the API response. Which file you edit depends on your server, but the header is the same everywhere.
Step 1: confirm the error is really CORS. Open the console, find the message, and check it says No 'Access-Control-Allow-Origin' header is present. If it says something else, like a preflight failure or a credentials problem, jump to the section below that matches. Do not fix the wrong one.
Step 2: add the header on the server. In a plain Node server it is one line:
res.writeHead(200, {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://127.0.0.1:8001",
});In Express, the same header on the response object:
app.get("/api/plain", (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8001");
res.json({ joke: "Why do programmers prefer dark mode? Because light attracts bugs." });
});Name your page's exact origin, not *, unless the API is genuinely public data with no login. * is fine for a public jokes API. It is the wrong choice for anything with user accounts, and the credentials section below shows why.
Step 3: reload and call it again. The verified test run for this tutorial did exactly this. Before the header, the fetch failed with TypeError: Failed to fetch and the console showed the blocked message. After adding "Access-Control-Allow-Origin": "*", the same call returned status 200 and the JSON parsed:
with-header OK status=200 joke=Why do programmers prefer dark mode? Because light attracts bugs.No JavaScript changed between the two runs. Only the server header changed, which is the point: this was never a frontend bug.
What about POST requests and the preflight?
A simple GET request goes straight out. A POST with a JSON body does not. Because Content-Type: application/json is not one of the browser's "simple" content types, the browser first sends an OPTIONS request, called a preflight, asking the server what is allowed. Only if the server answers the preflight with the right headers does the real POST go out.
The test run for this tutorial proved both halves. A POST to an endpoint with no OPTIONS handler failed before the real request ever left:
Access to fetch at 'http://127.0.0.1:8002/api/echo-no-preflight' from origin 'http://127.0.0.1:8001' 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.The same POST to an endpoint that answers OPTIONS with a 204 and the CORS headers succeeded, status 200, and the server received the body {"name": "Abd"}. The fix on the server side is an OPTIONS handler that returns the same origin header plus the headers the request will use:
app.options("/api/echo", (req, res) => {
res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8001");
res.setHeader("Access-Control-Allow-Headers", "content-type");
res.sendStatus(204);
});If you use Express, the cors npm package handles both the header and the preflight for you. That is the common route in real projects, and the header it sets is the same one verified above.
The wrong turn: `mode: "no-cors"` and other dead ends
Search this error and the first suggestion you will find is mode: "no-cors". It looks like a fix and it is a trap. no-cors tells the browser to send the request without CORS checks, but the response comes back opaque: your JavaScript cannot read it at all. The error disappears and so does the data, which is worse than an error, because now nothing tells you what went wrong.
Three other dead ends, in the order beginners usually try them:
- Adding the header in your JavaScript.
Access-Control-Allow-Originis a response header, set by the server. Sending it from the client does nothing. - Disabling the browser's security flags. Launching Chrome with web security off "works" on your machine and breaks everywhere else, including for every real user. Never ship that, and never ask a user to do it.
- A proxy as the first fix. Routing the API call through your own server, so the browser only ever talks to your own origin, is a legitimate pattern, and it is the right answer when you cannot change the API. But it is a workaround for a missing server fix, not a substitute for understanding the error, so try the header first.
How to verify the fix worked
Run this checklist, in order, and stop at the first step that fails:
- Console is clean. Reload the page, trigger the
fetch(), and confirm the CORS message is gone from the console. - The Network tab shows the header. Open DevTools, Network tab, click the API request, and check the Response Headers list contains
access-control-allow-originwith your page's origin as its value. - The data arrives.
console.logthe parsed JSON, or render it on the page as item 49 does, and confirm it is the real data, not an empty response. - The POST still works, if you have one. Trigger the POST with its JSON body and confirm status 200. If it fails now, the preflight OPTIONS request is the missing piece, not the main request.
- Logins still work, if you have them. With
credentials: "include", confirm the request succeeds and the server sees the cookie. A wildcard origin will fail this step even when the plain GET passes.
If all five pass, the fix is real. If step 2 shows the header but step 3 still fails, read the console message again, it has changed, and the new message names the next problem.
Try it yourself
Reproduce the error on purpose, then fix it. Serve a page on one port and a tiny API on another, using the two-server shape from this tutorial. Call the API with fetch() and read the console error. Then add the header on the API, reload, and watch the same call return 200. Then change the call to a POST with a JSON body, watch the preflight fail, and add the OPTIONS handler. Three errors, three fixes, and you will recognise each one for life.
Common mistakes
- Testing the API in the address bar. A working address bar never proves a
fetch()call will work. CORS applies to scripts, not navigation. Test with the realfetch()call from your page. - Fixing it in the JavaScript. The header belongs on the server response. Changing
fetch()options, adding request headers, or switching tomode: "no-cors"cannot grant your origin access. - Using
*with a logged-in API. A wildcard origin is refused the moment the request sends credentials. Name the exact origin and addAccess-Control-Allow-Credentials: true. - Forgetting the preflight. A GET works and the POST fails, because the POST sends an OPTIONS request first and the server has no handler for it. The console message says "preflight" when this is the cause.
- Fixing the wrong origin. The header must name the origin the page is actually served from, including the port.
http://localhost:3000andhttp://localhost:8001are different origins, and naming the wrong one changes nothing.
Frequently asked questions
Is a CORS error my fault?
Not in the way beginners fear. It means the API has not opted in to being read by your origin, which is the API owner's decision to make. If you own the API, add the header. If you do not, ask the owner, or route the call through your own server.
Can I just use * for everything?
For public data with no login, yes, and many public APIs do exactly that. For anything with user accounts, cookies or tokens, no: the browser refuses * with credentials, and an open wildcard on a private API is a real security hole.
Why is the JavaScript error just "Failed to fetch"?
The browser hides cross-origin details from your script on purpose, so a malicious page cannot probe another site's responses. The full reason is always in the console, which is why the console is step one.
Does CORS apply to <img> and <script> tags?
No. Loading an image, a stylesheet or a script from another origin is allowed, because the browser does not hand the content to your JavaScript. CORS only controls scripts reading another origin's data, which is what fetch() does.
My API is on the same domain but a different port. Is that cross-origin?
Yes. Origin means protocol plus domain plus port, so a different port is a different origin. That is why this error is so common in local development, where the page runs on one port and the API on another.
Follow the Frontend Developer Roadmap
Build modern, responsive websites and web apps with HTML, CSS, JavaScript and React. Free, step by step, at your pace.
View the Roadmap