Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

CORS Error: No Access-Control-Allow-Origin - Solutions (2026)

What is CORS Error?

CORS (Cross-Origin Resource Sharing) error occurs when a web application tries to access resources from a different domain, protocol, or port than the one serving the web page. This is a security feature implemented by browsers to prevent malicious websites from accessing sensitive data.

Common Causes

  • Server doesn't send proper CORS headers
  • Requesting from different domain/port (localhost:3000 → api.example.com)
  • Missing Access-Control-Allow-Origin header
  • Preflight request (OPTIONS) not handled properly
  • Credentials (cookies) sent without proper CORS configuration

Quick Fix (TL;DR)

Server-Side Solution (Node.js/Express)
// Install cors package
// npm install cors

const express = require('express');
const cors = require('cors');
const app = express();

// ✅ Enable CORS for all routes
app.use(cors());

// ✅ Or configure specific origins
app.use(cors({
    origin: 'http://localhost:3000',
    credentials: true
}));

Common Scenarios & Solutions

Scenario 1: Basic CORS Error - Missing Headers

The most common CORS error occurs when the server doesn't send the required Access-Control-Allow-Origin header.

Problem (Frontend)
// Frontend code (React/Vue/Vanilla JS)
fetch('https://api.example.com/users')
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));

// ❌ Error: CORS policy blocked
Solution (Node.js/Express Backend)
const express = require('express');
const app = express();

// ✅ Add CORS headers manually
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*'); // Allow all origins
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
});

app.get('/users', (req, res) => {
    res.json({ users: [] });
});

// ✅ Or use cors package (recommended)
const cors = require('cors');
app.use(cors());

Scenario 2: CORS with Credentials (Cookies)

When sending cookies or authentication headers, you need additional CORS configuration.

Problem (Frontend)
// Sending cookies with request
fetch('https://api.example.com/profile', {
    credentials: 'include' // Send cookies
})
.then(res => res.json())
.then(data => console.log(data));

// ❌ Error: Credentials flag is true, but Access-Control-Allow-Credentials is not
Solution (Backend)
// Node.js/Express
app.use(cors({
    origin: 'http://localhost:3000', // Must specify exact origin (not *)
    credentials: true // Allow credentials
}));

// Or manually
app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

Scenario 3: Preflight Request (OPTIONS) Not Handled

For certain requests (POST, PUT, DELETE with custom headers), browsers send a preflight OPTIONS request first.

Problem (Frontend)
// POST request with custom header
fetch('https://api.example.com/users', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer token123'
    },
    body: JSON.stringify({ name: 'John' })
});

// ❌ Error: Preflight request doesn't pass access control check
Solution (Backend)
// Handle OPTIONS preflight request
app.options('*', cors()); // Enable pre-flight for all routes

// Or manually
app.options('/users', (req, res) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.sendStatus(200);
});

app.post('/users', (req, res) => {
    // Your POST logic
    res.json({ success: true });
});

Scenario 4: Development Proxy (React/Vue)

During development, you can use a proxy to avoid CORS issues without changing backend code.

Solution (React - package.json)
{
  "name": "my-app",
  "version": "1.0.0",
  "proxy": "http://localhost:5000"
}
Solution (Vue - vue.config.js)
module.exports = {
    devServer: {
        proxy: {
            '/api': {
                target: 'http://localhost:5000',
                changeOrigin: true
            }
        }
    }
};

Backend Solutions by Framework

PHP (Laravel)

PHP CORS Middleware
// app/Http/Middleware/Cors.php
public function handle($request, Closure $next)
{
    return $next($request)
        ->header('Access-Control-Allow-Origin', '*')
        ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
        ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
}

Python (Flask)

Flask CORS
from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

# Or specific origins
CORS(app, origins=['http://localhost:3000'])

Java (Spring Boot)

Spring Boot CORS
@Configuration
public class CorsConfig {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                    .allowedOrigins("http://localhost:3000")
                    .allowedMethods("GET", "POST", "PUT", "DELETE");
            }
        };
    }
}

Best Practices

  • Don't use * in production - Specify exact allowed origins for security
  • Use CORS package - Don't manually set headers (error-prone)
  • Handle preflight requests - Always respond to OPTIONS requests
  • Use proxy in development - Avoid CORS issues during local development
  • Test with credentials - If using cookies, test with credentials: 'include'
  • Check browser console - CORS errors show detailed messages in console
  • Use HTTPS in production - Mixed content (HTTP/HTTPS) can cause CORS issues

Related Errors

Key Takeaways
  • CORS is a browser security feature that blocks cross-origin requests
  • Server must send Access-Control-Allow-Origin header to allow requests
  • Use cors package in Node.js/Express for easy CORS configuration
  • Credentials (cookies) require specific origin (not *) and credentials: true
  • Preflight OPTIONS requests must be handled for POST/PUT/DELETE
  • Use development proxy to avoid CORS during local development

Frequently Asked Questions


Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.