React Tutorial

73 lessons

0 / 73 completed0%
Beginner Basics
Intermediate Topics
Advanced Concepts
Lesson 1 of 73
Step 1 of 735 min

Fix CORS Error in React - No Access-Control-Allow-Origin Header

When you call an API from React running on localhost:3000, the browser blocks the request if the API doesn't allow cross-origin requests. This is CORS (Cross-Origin Resource Sharing) protection.

Error Message:

Example
Access to fetch at 'https://api.example.com' from origin 'http://localhost:3000' 
has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present

Understanding the Problem

The browser checks if the API server explicitly allows requests from your origin (localhost:3000). If the API doesn't send the right headers, the browser blocks the response.

Solution 1: Development Proxy (Quick Fix)

Add this to your package.json:

Example
{
  "proxy": "https://api.example.com"
}

Change your fetch calls:

Example
// Before
fetch('https://api.example.com/users')

// After
fetch('/users')

The React dev server forwards requests to the API. CORS error disappears.

Solution 2: Backend Configuration (Production Fix)

If you control the backend, add CORS headers. For Express.js:

Example
const cors = require('cors');

app.use(cors({
  origin: 'http://localhost:3000',  // development
  // origin: 'https://yourapp.com', // production
  credentials: true
}));

Solution 3: Backend Proxy (Best Practice)

Create an endpoint in your backend that calls the external API:

Example
// Node.js backend
app.get('/api/weather', async (req, res) => {
  const response = await fetch('https://external-api.com/data');
  const data = await response.json();
  res.json(data);
});

Your React app calls your backend:

Example
fetch('http://localhost:5000/api/weather')

Backend-to-backend calls don't have CORS restrictions.

Common Mistakes

Using mode: 'no-cors'

Example
fetch(url, { mode: 'no-cors' })  // Don't do this

This sends the request but you can't read the response. The response becomes "opaque" - completely useless.

CORS Browser Extensions

Chrome extensions like "CORS Unblock" only work in development. They don't solve production issues.

Which Solution to Use

Scenario Solution
Development Use proxy in package.json
You own the API Configure CORS on backend
Third-party API Create backend proxy
Production Backend proxy or proper CORS config

Key Points

CORS is a security feature, not a bug. The proper fix depends on whether you control the API server. For third-party APIs, always route through your backend.