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.
// 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
}));
The most common CORS error occurs when the server doesn't send the required Access-Control-Allow-Origin header.
When sending cookies or authentication headers, you need additional CORS configuration.
For certain requests (POST, PUT, DELETE with custom headers), browsers send a preflight OPTIONS request first.
During development, you can use a proxy to avoid CORS issues without changing backend code.
// 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
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());
// 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
// 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();
});
// 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
// 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 });
});
{
"name": "my-app",
"version": "1.0.0",
"proxy": "http://localhost:5000"
}
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://localhost:5000',
changeOrigin: true
}
}
}
};
// 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');
}
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'])
@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");
}
};
}
}
CORS (Cross-Origin Resource Sharing) error occurs when a browser blocks a request from one origin (domain/port) to another origin due to security restrictions. The server must explicitly allow cross-origin requests by sending proper CORS headers.
Fix CORS by configuring your server to send Access-Control-Allow-Origin header. In Node.js, use the cors package. In development, you can use a proxy in React/Vue to avoid CORS issues.
CORS is a browser security feature. Tools like Postman or curl don't enforce CORS because they're not browsers. The error only occurs when making requests from JavaScript in a web page.
You can disable CORS in Chrome with --disable-web-security flag, but this is only for testing. Never disable CORS in production or for regular browsing as it's a critical security feature.
A preflight request is an OPTIONS request sent by the browser before the actual request for POST/PUT/DELETE with custom headers. The server must respond to OPTIONS with proper CORS headers.
Explore 500+ free tutorials across 20+ languages and frameworks.