Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 980
bernatfortet Avatar asked Sep 04 '17 20:09

bernatfortet


People also ask

How do you enable CORS in Create react app?

Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. then you can get the create-react-app server to proxy your request to your api server quite easily.

How do you resolve CORS issues in react from frontend?

There are several ways we can overcome this issue: Make REST API calls from the same domain as xkcd. Edit the CORS settings of xkcd's server. Make REST API calls from our own backend server.

How do I add CORS support to API?

You can add CORS support to an API proxy by attaching an "Add CORS" policy to the API proxy when you create it. To add this policy, select the Add CORS headers checkbox in the Security page of the Build a Proxy wizard.


1 Answers

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;
    };
  },
};

like image 143
QuarkleMotion Avatar answered Oct 05 '22 13:10

QuarkleMotion