What is a CORS Preflight Request?
Answer:
A CORS Preflight request is a special OPTIONS HTTP request automatically sent by the browser before the actual request, to determine whether the cross-origin request is safe and allowed by the server.
It occurs when a client makes a request with:
- Custom headers (e.g.,
Authorization
, X-Custom-Header
) - HTTP methods other than GET, POST, or HEAD (e.g., PUT, DELETE)
- Content-Type other than
application/x-www-form-urlencoded
, multipart/form-data
, or text/plain
How does a Preflight Request work?
- Browser sends an OPTIONS request to the server with headers like:
Access-Control-Request-Method
Access-Control-Request-Headers
Origin
- Server responds with appropriate CORS headers if it allows the request:
Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Max-Age
(optional, to cache preflight response)
- If approved, the browser proceeds with the actual request.
Example – Preflight Flow
Browser Request (Preflight - OPTIONS)
http
OPTIONS /api/resource HTTP/1.1
Origin: https://client.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type
Server Response
http
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://client.com
Access-Control-Allow-Methods: PUT, GET, POST
Access-Control-Allow-Headers: Content-Type
Handling CORS Preflight in Java (Spring Boot Example)
1. Using @CrossOrigin
:
java
@CrossOrigin(origins = "https://client.com", methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
@RestController
public class MyController {
@PutMapping("/api/resource")
public ResponseEntity<?> updateResource() {
return ResponseEntity.ok("Updated");
}
}
2. Global Configuration with CorsFilter:
java
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://client.com")
.allowedMethods("GET", "POST", "PUT", "DELETE")
.allowedHeaders("*")
.allowCredentials(true);
}
};
}
Common Interview Points
- CORS is enforced by browsers, not by servers.
- Preflight requests only apply to cross-origin requests with non-simple methods or headers.
- The OPTIONS method is key to preflight requests.
- Misconfigured CORS can cause errors like "CORS policy: No 'Access-Control-Allow-Origin' header...".
- Use tools like Postman or browser DevTools to debug preflight issues.