Understanding CORS When Using Ruby on Rails As An API
How to deal with cross-origin-resource sharing errors, the right way
Published in
4 min readOct 12, 2020
The typical developer response to a CORS problem is…
- Go to Stack Overflow
- Copy/paste a code solution (that has warnings in the comments)
- Commit code to Github
… without ever understanding what is going on.
Don’t be that developer.
It you’ve ever worked on a app where the frontend and backend are separate application, CORS was involved.
This is what you need to know
- Modern browsers block cross-origin requests by default.
- Code executed on different domains, protocols, or ports have different origins. A request between them is “cross-origin”.
- CORS does not prevent cross-origin requests. It allows them when configured to do so.
- Frontend (Node+ReactJS) and backend (Rails API) apps running on different ports will experience communication problems unless CORS is configured.
CORS in practise
Let’s create a super quick Node/ReactJS frontend and Rails API backend, so we can experience CORS…