How to config CORs in Reactjs on Production environment

3049 views javascript
4

I have a problem when I deploy react app to Heroku:

Access to fetch at 'https://rs-yoga-prod.herokuapp.com/' from origin 'https://rs-react-prod.herokuapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header has a value 'https://rs-react-prod.herokuapp.com/' that is not equal to the supplied origin. 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.

I've researched and added proxy in package.json like this:

"proxy": {
    "dev": { "target": "http://localhost:4000"},
    "prod": { "target": "https://rs-yoga-prod.herokuapp.com" }
}

But it still show error, what did I'm wrong ?

server URL: https://rs-yoga-prod.herokuapp.com
client URL: https://rs-react-prod.herokuapp.com

You can access these URL for more detail, thanks.

answered question

1 Answer

7

CORS has to be handled at the backend side. Backend has to send CORS headers on the OPTIONS request.

Follow are the list of headers need to return by backend for enabling CORS.

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET , DELETE , PUT , OPTIONS
Access-Control-Allow-Headers: Content-Type

Read more about CORS from mdn - https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS

posted this

Have an answer?

JD

Please login first before posting an answer.