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.
Previous
What is the difference between API keys and OAuth 2.0?
Next
What is the RFC 7807 Problem Details format for REST API errors?
More REST API Design Questions
View all →- Intermediate What is HATEOAS and how is it implemented?
- Intermediate What are the main API versioning strategies in REST and what are their tradeoffs?
- Intermediate What are the pagination strategies in REST APIs?
- Intermediate What is rate limiting and how is it communicated in REST APIs?
- Intermediate How does HTTP caching work in REST APIs with ETag and Cache-Control?