debugjavascriptMajorpending
Debug: CORS preflight OPTIONS request fails
Viewed 0 times
CORSpreflightOPTIONSAccess-Controlcross-origin
Error Messages
Problem
Browser blocks cross-origin requests with 'No Access-Control-Allow-Origin header' even though GET works. The preflight OPTIONS request fails.
Solution
The browser sends an OPTIONS preflight for non-simple requests. Your server must handle it:
// Express.js
app.options('*', cors()); // Handle preflight
app.use(cors({
origin: 'https://your-frontend.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
- Custom headers (Authorization, X-Custom-*)
- Content-Type other than form-urlencoded, multipart, text/plain
- Methods other than GET, HEAD, POST
- API gateway/load balancer strips CORS headers
- OPTIONS not routed to your handler (nginx/Apache config)
- credentials: true requires specific origin (not wildcard *)
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
return 204;
}
- Ensure OPTIONS method is handled:
// Express.js
app.options('*', cors()); // Handle preflight
app.use(cors({
origin: 'https://your-frontend.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
- What triggers preflight:
- Custom headers (Authorization, X-Custom-*)
- Content-Type other than form-urlencoded, multipart, text/plain
- Methods other than GET, HEAD, POST
- Common issues:
- API gateway/load balancer strips CORS headers
- OPTIONS not routed to your handler (nginx/Apache config)
- credentials: true requires specific origin (not wildcard *)
- Nginx fix:
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '$http_origin';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
return 204;
}
Why
Preflight is a security mechanism. The browser asks the server if the actual request is allowed before sending it.
Revisions (0)
No revisions yet.