bernatfortet
bernatfortet

Reputation: 2312

Create React App adding CORS header

I'm trying to figure out where to add the "Access-Control-Allow-Origin" header to my create-react-app dev Server config.

So far I'm adding it to config/webpackDevServer.config.js without much luck.

Any idea on where I could add it?

thanks!

Upvotes: 6

Views: 10561

Answers (3)

QuarkleMotion
QuarkleMotion

Reputation: 874

Here is a recipe based on @tlfu 's answer for those that are using react-app-rewired. In this case you'll need to define a root level config-overrides.js file containing the following:

module.exports = {
  // Extend/override the dev server configuration used by CRA
  // See: https://github.com/timarney/react-app-rewired#extended-configuration-options
  devServer: function(configFunction) {
    return function(proxy, allowedHost) {
      // Create the default config by calling configFunction with the proxy/allowedHost parameters
      // Default config: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/config/webpackDevServer.config.js
      const config = configFunction(proxy, allowedHost);

      // Set loose allow origin header to prevent CORS issues
      config.headers = {'Access-Control-Allow-Origin': '*'}

      return config;
    };
  },
};

Upvotes: 8

tlfu
tlfu

Reputation: 171

I hit this problem. In my case, I'm doing something a bit unusual. I'm serving up my React app from a Salesforce Visualforce page, so the page is served from the visual.force.com domain. I've wired up the Visualforce page so that I can run the app locally using Webpack Dev Server and a tunnel (ngrok) to proxy the requests from Salesforce through to localhost. When my app tries to load resources from the apps "public" folder I'd get errors like this:

Failed to load https://xxxx.ngrok.io/scss/bootstrap.scss: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://xxxx.visual.force.com' is therefore not allowed access.

I tried adding devServer: {headers: {'Access-Control-Allow-Origin': '*'}} to the webpack.config.dev.js configuration object, but this didn't work. I found that I had to add the following to the webpackDevServer.config.js file instead: headers: {'Access-Control-Allow-Origin': '*'} (note that "headers" is a top level config property, not nested within the "devServer" property). I read where when you run Webpack Dev Server via the Node API, it doesn't read the devServer config object from your webpack config file.

Upvotes: 2

nikrb
nikrb

Reputation: 153

Apologies if I have the wrong end of the stick, but from your question I'm guessing you're using a backend api with react front end. afaik you don't need cors, just add a proxy to your client/frontend package.json: "proxy": "http://localhost:5000/" Dan does say this is only for simple cases, but I hope it helps

Upvotes: 0

Related Questions