Simple vs. Preflighted Requests
Deslize para mostrar o menu
When working with CORS, it is important to understand the distinction between simple requests and those that require a preflight check. Browsers classify some cross-origin HTTP requests as simple if they meet certain criteria. A simple request is one that uses only the GET, HEAD, or POST HTTP methods and restricts headers to a specific set of safe values. For a POST request to qualify as simple, its Content-Type must be either text/plain, multipart/form-data, or application/x-www-form-urlencoded. Additionally, the request must not use custom headers or include credentials like cookies unless specifically allowed. These restrictions are designed to ensure that simple requests are safe and predictable, minimizing the risk of unintended side effects on the target server.
Requests that do not meet the criteria for a simple request trigger what is known as a preflight request. Before sending the actual request, the browser sends an HTTP OPTIONS request to the target server. This preflight request asks the server whether the actual request is safe to send, based on the HTTP method and headers that will be used. Preflight requests are automatically initiated by the browser when:
- The request uses an HTTP method other than
GET,HEAD, orPOST; - The request includes headers outside the set of simple headers (such as custom headers or certain authentication headers);
- The
Content-Typeis not one of the three allowed for simple POST requests.
The server must respond to the preflight request with the appropriate CORS headers, indicating which origins, methods, and headers are permitted. If the server's response does not allow the intended cross-origin request, the browser will block it before it reaches the server application.
OPTIONS /api/data HTTP/1.1
Origin: https://example-client.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: X-Custom-Header
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://example-client.com
Access-Control-Allow-Methods: PUT
Access-Control-Allow-Headers: X-Custom-Header
Access-Control-Max-Age: 600
In this example, the browser is about to send a PUT request with a custom header (X-Custom-Header) to /api/data on a different origin. Because PUT is not a simple method and the request includes a non-standard header, the browser first sends an OPTIONS preflight request. The server responds with CORS headers that explicitly allow the origin, method, and header requested. If the response did not include these headers, or if any value was missing, the browser would block the actual request. This process ensures that servers remain in control of which cross-origin requests are permitted, reducing the risk of unexpected or malicious interactions.
Obrigado pelo seu feedback!
Pergunte à IA
Pergunte à IA
Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo