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
12
Related Errors
JavaScript
RangeError: Maximum Call Stack Size Exceeded
The function calls itself recursively too many times, exceeding the stack size limit.
Frontend
WebSocket Connection Failed
The WebSocket connection could not be established or was closed unexpectedly.
JavaScript
ReferenceError: X is not defined
The code references a variable or function that hasn't been declared.
ERR_MODULE_NOT_FOUND
Node.js
ERR_MODULE_NOT_FOUND
Node.js cannot find the specified ES module file.