Understanding CORS When Using Ruby on Rails As An API

How to deal with cross-origin-resource sharing errors, the right way

GreekDataGuy
Ruby Daily

--

Photo by ThisIsEngineering from Pexels

The typical developer response to a CORS problem is…

  1. Go to Stack Overflow
  2. Copy/paste a code solution (that has warnings in the comments)
  3. 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…

--

--