What is CORS and how does a preflight request work?

Answer

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts which origins (domain+port+protocol) can make requests to an API from JavaScript. When a browser script on https://app.com calls https://api.example.com, it is a cross-origin request. For "non-simple" requests (non-GET/POST, custom headers, or JSON body), the browser first sends an OPTIONS preflight request asking the server if the actual request is allowed. The server responds with CORS headers: Access-Control-Allow-Origin: https://app.com, Access-Control-Allow-Methods: GET, POST, PUT, Access-Control-Allow-Headers: Authorization, Content-Type. If the preflight succeeds, the browser sends the actual request. Access-Control-Allow-Credentials: true is required if the request includes cookies. Avoid Access-Control-Allow-Origin: * with credentials.