React Tutorial
73 lessons
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:
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:
{
"proxy": "https://api.example.com"
}
Change your fetch calls:
// 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:
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:
// 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:
fetch('http://localhost:5000/api/weather')
Backend-to-backend calls don't have CORS restrictions.
Common Mistakes
Using mode: 'no-cors'
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.