ga-wdi-boston / capstone-project

Other
3 stars 29 forks source link

No 'Access-Control-Allow-Origin' issue. Cannot wire React App to Rails API #884

Open rotondozer opened 6 years ago

rotondozer commented 6 years ago

Both my React App and my Rails server are being hosted locally. Curl scripts work fine, so I know the API is not the issue. I know how to fix this problem when deployed to Heroku (changing the 'client_origin' in config vars) but I can't figure out how to 'allow' this local resource access. Since I'm building off of a create-react-app template, I do not have all the same files that are provided with the browser template. My guess is that the browser template takes care of this when running a local front end with a local back end. I have tried querying for a resource that does not require authorization, and I have tried this same exact sign-up AJAX request I've used on previous projects.

The exact message I'm receiving in the Chrome console is: XMLHttpRequest cannot load http://localhost:4741/sign-up/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 400.

I'm guessing this has something to do with CORS but I don't know if I should be trying to allow this resource by changing something in my Rails API, or adding some type of validation in my React App.

rotondozer commented 6 years ago

Added this code snippet to application.rb

config.action_dispatch.default_headers = { 'Access-Control-Allow-Origin' => 'http://localhost:3000', 'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")