Enabling CORS in Create React App utility

I need to use CORS node module in React created using create-react-app utility.

Since its a utility I am not able to tweak inside and inject CORS into preconfigured EXPRESS module.

How can we achieve this?

3

2 Answers

If you are needing this for development and wanting to access an api from your react app but getting an error like this-

Failed to load The 'Access-Control-Allow-Origin' header has a value ' that is not equal to the supplied origin. Origin ' is therefore not allowed access. 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.

create-react-app uses the webpack development server to serve your react app.

So if your react app is being served from and the api you want to connect to is at you can simply add a proxy value into your react app's package.json file like this-

proxy: "", 

then from your react app call your api like

fetch('/tables').then(....) 

the request will be sent to the create-react-app server which will send it on to the api server and return the results for you.

Full details here Proxying API Requests in Development

4

SIMPLER SOLUTION IS:

Because the server from create-react-app is only used during development, then you can use additional extensions on each browser to resolve the issue. Here are some extensions that you can use to solve CORS problems during development stage:

There is Whitelist features that can use to activated the extension in only specified websites. So don't worry about the security.

Of course, at the production stage you can solve CORS problems on your respective server, so at this stage, the browser extension is no longer needed.

3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like