This minimal roda app demonstrates a cors preflight and subsequent POST request using curl.
- The
-H Origin:
header identifies the caller making the preflight request. (i.e. The app which wishes to make cross origin requests to this endpoint.) - The
-X OPTIONS
method specifier defines this as a preflight request.
curl --head \
-H 'Origin: https://pizza-app.example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: X-Requested-With' \
-X OPTIONS \
https://rack-cors-roda.herokuapp.com/pizza/toppings
- The origin which may consume data from this endpoint.
- Methods the origin can use with this endpoint.
- Headers the endpoint will allow the origin to read. (A default set is allowed.)
- Seconds before another preflight request is required. (Technically, the number of seconds a preflight response can be cached by the browser.)
- Which headers are allowed during the subsequent request.
Access-Control-Allow-Origin: https://rack-cors-roda.herokuapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD
Access-Control-Expose-Headers:
Access-Control-Max-Age: 7200
Access-Control-Allow-Headers: X-Requested-With
curl \
--request POST 'https://rack-cors-roda.herokuapp.com/pizza/toppings' \
--header 'Content-Type: text/plain' \
--data-raw '{ "topping": "cheese" }'
{"your_topping":"cheese"}
- Testing your cors configuration using curl or postman does not guarantee browser requests will work. (YMMV)
- The cors standard is defined within the JavaScript Fetch API.
- Configuring cors on your API necessitates coordination with your front-end app.
- A cors preflight request lets the browser inquire if cors is supported and whether cors headers are understood. (Browsers make preflight requests as needed so front-end developers don't usually need to code them.)
- This curl testing methodology comes from this SO answer.
- Using the rack-cors gem:
- Multiple origins are allowed
- Multiple allow blocks are allowed
- Origins must include scheme and no trailing slash
- Using wildcard origin (
Origins '*'
) enables requests from anywhere (i.e. calls to a public API) - Cookies sent from a cors endpoint with wildcard origin are not accepted by the calling browser. (This prevents abuse from public APIs with wildcard origins.)