Running a React/Rails app locally

Viewed 2036

I am trying to run an application locally which has React/Redux front-end and communicates with a rails api. In my .env file I am referencing the port which is running my api (rails s has it running on port as API_URL 3000) and my react dev server is referenced in HOST running on localhost:3003.

When I go to localhost:3003 and have my react font-end up, I get the following error when i send requests to my api: Bothy me .env files are also pointing at the correct ports on localhost.

XMLHttpRequest cannot load http://localhost:3000/users_company. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3003' is therefore not allowed access. The response had HTTP status code 500.

Any ideas ?

3 Answers

For anyone migrating to this answer who is using Webpack but not Create React App, you can still set up a proxy if you're using webpack-dev-server. This is true for any JavaScript front-end on Webpack, not just React.

For example, I'm running my front-end on localhost:8080 and Rails is on localhost:3000. In your webpack.config.js file in the section where you define devServer:

  devServer: {
    // ...
    // Rails backend runs on localhost:3000
    proxy: {
      '/': {
        target: 'http://localhost:3000',
        secure: false
      }
    }
  },

You can read more about configuration options in the Webpack docs here and in the http-proxy-middleware docs here (the underlying dependency).

Related