Skip to content

How to Fix CORS Error in JavaScript Fetch

DodaTech Updated 2026-06-24 2 min read

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 cors npm package with whitelisted origins for production.

Common Mistakes with cors error

  1. Non-exhaustive pattern matches that compile with warnings then crash at runtime
  2. Misunderstanding that String is [Char] with poor performance for large text operations
  3. Using foldl instead of foldl' 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

### Why does CORS exist if it causes so many errors?

CORS (Cross-Origin Resource Sharing) is a security mechanism that prevents malicious scripts on one site from accessing sensitive data on another site without permission. It protects users from cross-site request forgery and data theft. The browser enforces it, not the server.

What is a preflight request in CORS?

For non-simple requests (PUT, DELETE, custom headers, or non-standard content types), the browser sends an OPTIONS preflight request before the actual request. The server must respond with the appropriate CORS headers for the preflight to succeed. If the preflight fails, the main request is never sent.

Can I disable CORS in my browser for development?

Yes, but only for local testing. Chrome: --disable-web-security --user-data-dir=/tmp/chrome_dev. Firefox: about:config set security.fileuri.strict_origin_policy to false. Never use these flags for regular browsing as they disable critical security protections.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro