CORS Error
The browser blocks cross-origin requests due to same-origin policy restrictions.
Explanation
CORS (Cross-Origin Resource Sharing) errors occur when the browser blocks a request from a web page to a different domain, port, or protocol than the server that served the page. This is a security feature to prevent malicious websites from accessing data from other origins. The error message indicates the request was blocked by the Access-Control-Allow-Origin header policy. CORS requests may fail on preflight (OPTIONS) requests or actual requests.
Common Causes
- Server missing CORS headers
- Origin not in allowed list
- Preflight OPTIONS request not handled
- Credentials mode mismatch
- Requested headers not allowed
Solution
Configure the server to send appropriate CORS headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods, Access-Control-Allow-Headers. In Laravel, use the cors middleware (built-in since Laravel 7). Check that the server responds to OPTIONS preflight requests. Ensure the frontend and backend have matching CORS configurations. For development, configure your API server to allow all origins (not for production). Use a reverse proxy for development.
Code Example
// Frontend making cross-origin request
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer token123'
}
})
.then(res => res.json())
.catch(err => console.log('CORS error:', err));
// Laravel: configure CORS in config/cors.php
return [
'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['https://myfrontend.com'],
'allowed_headers' => ['*'],
];
// Express.js CORS configuration
const cors = require('cors');
app.use(cors({
origin: 'https://myfrontend.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization']
}));
// Nginx proxy to avoid CORS entirely
location /api/ {
proxy_pass http://backend:3000/;
}
Error Information
Language
javascript
Difficulty
Intermediate
Views
13
Related Errors
Frontend
ResizeObserver Loop Limit Exceeded
A ResizeObserver callback triggered layout changes that caused another resize, creating an infinite loop.
JavaScript
TypeError: Cannot Read Property of Undefined
The code tries to access a property or method on an undefined or null value.
Frontend
Hydration Mismatch (SSR)
The server-rendered HTML doesn't match what the client-side JavaScript expected to render.
ECONNREFUSED
Database
ECONNREFUSED
The network connection was refused by the target server.