Skip to content

How to Fix CORS Error on Localhost

DodaTech 1 min read

In this tutorial, you'll learn about How to Fix CORS Error on Localhost. We cover key concepts, practical examples, and best practices.

The Problem

Your frontend app makes a fetch request to a different port and the browser console shows:

Access to fetch at 'http://localhost:4000/api/data' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Browsers block cross-origin HTTP requests initiated by scripts for security reasons. In development, your frontend runs on one port (e.g., 3000) and your backend on another (e.g., 4000), triggering the CORS policy.

Quick Fix

Step 1: Add CORS headers to the server

Express.js:

npm install cors
const cors = require("cors");
app.use(cors());

Or configure specific origins:

app.use(cors({
  origin: "http://localhost:3000",
  methods: ["GET", "POST"],
}));

Python Flask:

pip install flask-cors
from flask_cors import CORS
CORS(app)

Step 2: Use a proxy in the frontend

React (Create React App):

Add to package.json:

{
  "proxy": "http://localhost:4000"
}

Vite:

In vite.config.js:

export default {
  server: {
    proxy: {
      "/api": "http://localhost:4000",
    },
  },
};

Now fetch from /api/data instead of http://localhost:4000/api/data.

Step 3: Disable CORS in the browser (development only)

Start Chrome with CORS disabled:

google-chrome --disable-web-security --user-data-dir=/tmp/chrome-dev

Prevention

  • Add CORS middleware early in development to avoid wasting time later.
  • Use environment variables to configure allowed origins per environment.
  • In production, restrict CORS to specific domains, not wildcards.
  • For development, use a proxy configuration instead of CORS headers -- it is simpler and matches production behavior better.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro