How to Fix CORS Error in JavaScript Fetch
In this tutorial, you'll learn about How to Fix CORS Error in JavaScript Fetch. We cover key concepts, practical examples, and best practices.
The Problem
The browser throws CORS error: No 'Access-Control-Allow-Origin' header is present when a frontend script tries to fetch a resource from a different origin than the page's own origin.
Quick Fix
Step 1: Check the browser console
The error message tells you which header is missing:
fetch('https://api.othersite.com/data')
.then(res => res.json())
.catch(err => console.log(err.message));
Failed to fetch: CORS request did not succeed
Check the Network tab in DevTools for the actual CORS error details.
Step 2: Configure CORS on the backend
For Express.js, use the cors package:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({ origin: 'https://myfrontend.com' }));
app.get('/data', (req, res) => res.json({ message: 'OK' }));
For a custom middleware:
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', 'https://myfrontend.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
});
Step 3: Use a proxy for development
In your development server, proxy API requests:
// vite.config.js
export default {
server: {
proxy: {
'/api': 'https://api.othersite.com'
}
}
};
// Now fetch from the same origin
fetch('/api/data').then(res => res.json());
Step 4: Use mode: 'no-cors' only for simple requests
No-cors mode sends the request but hides the response:
fetch('https://api.othersite.com/data', { mode: 'no-cors' })
.then(res => console.log(res));
Response { type: 'opaque', status: 0, ... }
The response is opaque and cannot be read. Use this only for analytics pings or logging.
Prevention
- Configure CORS headers on your backend API server.
- Use environment-specific origins in CORS configuration.
- In development, use a proxy server to avoid CORS entirely.
- Use
corsnpm package with whitelisted origins for production.
Common Mistakes with cors error
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro