How to Fix “Blocked by CORS Policy” Error in JavaScript (Step-by-Step Guide)

Published: (February 20, 2026 at 11:34 PM EST)
3 min read
Source: Dev.to

Source: Dev.to

Introduction

If you are building a web application and see this error in your browser console:

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

This is one of the most common issues beginners face when working with JavaScript and APIs.

In this article you will learn:

  • What CORS is
  • Why this error happens
  • How to fix it in Node.js (Express)
  • How to fix it in PHP
  • Best practices for production

What Is CORS?

CORS (Cross‑Origin Resource Sharing) is a browser security feature. A request is considered cross‑origin when:

  • Your frontend runs on http://localhost:3000
  • Your backend runs on https://api.example.com

Because these origins are different, the browser blocks the request unless the server explicitly allows it.

Important: CORS is enforced by the browser, not by the server.

Why the CORS Error Happens

CORS errors occur because the backend server does not send the correct HTTP headers. The browser checks for headers like:

Access-Control-Allow-Origin

If the header is missing, the browser blocks the request. This means you cannot fix CORS from the frontend alone; it must be configured on the backend.

Solution 1: Fix CORS in Node.js (Express)

  1. Install the CORS middleware:
npm install cors
  1. Update your Express server:
const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors());

app.get('/api/data', (req, res) => {
  res.json({ message: "CORS is fixed!" });
});

app.listen(5000, () => console.log("Server running on port 5000"));
  1. Restart the server and test your request again.

Solution 2: Fix CORS in PHP

Add the following headers at the top of your PHP file:

This allows cross‑origin requests.

Important: Do Not Use “*” in Production

Using:

header("Access-Control-Allow-Origin: *");

allows requests from any domain, which is unsafe for production. Instead, specify your allowed domain:

header("Access-Control-Allow-Origin: https://yourdomain.com");

Why Postman Works but the Browser Fails

  • Postman works because it does not enforce CORS restrictions.
  • Browsers fail because they enforce CORS as a security rule.

Quick Debug Checklist

  • Confirm CORS headers are set on the backend.
  • Restart the server after making changes.
  • Clear the browser cache.
  • Check the browser console for updated messages.

Conclusion

The “Blocked by CORS Policy” error is not a JavaScript bug; it is a browser security rule. Once you understand that CORS must be configured on the backend, the solution becomes straightforward.

0 views
Back to Blog

Related posts

Read more »