Web Technology Basics
JavaScript on a page at https://app.example.com uses fetch to send a POST request with a body of Content-Type application/json to https://api.example.net/orders. Which of the following correctly describes how CORS behaves in this case?
- ACORS also works outside browsers, so without the server's permission even a POST sent from a command-line tool is stopped along the network
- BThe browser first sends a preliminary check (a preflight) with the OPTIONS method, and sends the actual POST only if the server returns permission in its headers
- CRequests to a different origin are always sent without any check, and the page's JavaScript can read the response even if the server adds nothing to it
Show answer and explanation
Answer: B. The browser first sends a preliminary check (a preflight) with the OPTIONS method, and sends the actual POST only if the server returns permission in its headers
CORS is a mechanism that allows requests to other origins, and the reading of their responses, which the same-origin policy restricts, within the scope the server permits. A POST with Content-Type application/json is a kind of request that a simple form submission cannot produce, so the browser first uses OPTIONS to state the method and headers it will use and asks for permission. If the server's response does not grant permission with headers such as Access-Control-Allow-Origin, the browser does not send the actual request. CORS is a rule enforced by the browser, so the server must protect itself separately with authentication and permission checks.
- A. CORS is a check performed by browsers and does not stop requests from tools other than browsers. Server-side authentication and permission checks are needed separately.
- B. Correct. For a POST with an application/json body, permission is confirmed with a preflight before sending.
- C. Scripts can read responses from other origins only when the server permits it with headers such as Access-Control-Allow-Origin.