Kimkorng / Note / 11 AUG, 2025

How to Fix CORS Policy Error in JavaScript

If you’ve been building something with JavaScript, there’s a good chance you’ve seen this:

Access to fetch at 'https://example.com' from origin 'http://localhost:3000' has been blocked by CORS policy

It’s one of the most common errors that new web developers search for. And honestly, even experienced developers sometimes get stuck on it.

How to Fix CORS Policy Error in JavaScript

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It’s a browser security rule.
The idea is simple: if your website is running on domainA.com, it can’t just grab data from domainB.com unless domainB.com says, “It’s fine.”

This is to protect users from malicious scripts that try to steal data from other sites.

Why the Error Happens

You see the error when your frontend (React, Vue, plain JS, etc.) is trying to call an API that isn’t on the same domain, and that API hasn’t allowed your site to connect.

For example:

  • Your app is on http://localhost:3000
  • The API is on https://api.example.com
  • The API doesn’t include Access-Control-Allow-Origin for your site
  • The browser blocks the request

How to Fix It

1. If You Control the API

  • Go to the backend code.
  • Add the CORS header:
plaintext
Access-Control-Allow-Origin: *

You can replace * with a specific domain if you want to limit access.

2. If You Don’t Control the API

  • Use a proxy server. Your frontend calls your own backend, and your backend calls the API.
  • Many frameworks have built-in proxy settings. For example, in Create React App, add this to package.json:
json
"proxy": "https://api.example.com"

3. For Quick Testing

  • You can disable CORS checks in your browser temporarily. But don’t use this in production—it’s unsafe.

A Few Things to Remember

  • CORS is a browser thing. If you make the same request with curl or from Node.js, it often works because there’s no browser blocking it.
  • The right fix is usually on the server, not in the frontend.

If you’re stuck, don’t waste hours blaming your JavaScript code. Check the network tab in DevTools. Look at the response headers. If Access-Control-Allow-Origin is missing or wrong, that’s your problem.

Most developers run into this at some point. The good news? Once you understand why it happens, fixing it becomes quick.

Share: