How to Fix CORS Error When Calling an API (2025 Guide)
Published April 2025 · 5 min read
The CORS error is the most frustrating error in web development. Here's how to actually fix it.
What the Error Looks Like
Access to fetch at 'https://api.example.com' from origin
'http://localhost:3000' has been blocked by CORS policy
Why It Happens
Browsers block requests from one domain to another for security. Your frontend (localhost:3000) can't call a different domain's API unless that API explicitly allows it.
Fix 1: Server-Side (The Real Fix)
Add CORS headers to your API response:
// Node.js/Express
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
next();
});
// Or use the cors package
const cors = require('cors');
app.use(cors());
Fix 2: Proxy (If You Don't Control the API)
In development, proxy through your dev server:
// vite.config.js
export default {
server: {
proxy: { '/api': 'https://api.example.com' }
}
}
Fix 3: Serverless Function
Create a small serverless function (AWS Lambda, Vercel, Netlify) that calls the API server-side and returns the data.
What NOT to Do
- ❌ Don't disable CORS in your browser
- ❌ Don't use CORS proxy services in production
- ❌ Don't set Allow-Origin to * for authenticated APIs
Related
- JSON Formatter — format API responses
- URL Encoder