简体   繁体   中英

Access-Control-Allow-Origin and handling from localhost

So, in my React app, I am making some endpoint calls to different servers and I also have withCredentials set to true, since I pass some token/cookie along with all the requests.

Now, how can I make this work on localhost seamlessly? Since I have withCredentials to true, the Access-Control-Allow-Origin needs to have specific origin and cannot have * (so if host is localhost:3000, it is not allowed and I get CORS error)

Any ideas on making this work both for local testing and for env deployments?

Create a list of origins that are allowed to access each environment. Select a means to store this data apropriate for your backend environment.

In your server-side code, read the Origin request header and compare it to the list of allowed origins for the environment you are running in. If it matches one of them, add an Access-Control-Allow-Origin header with that value to the response.


For example, if you are using Node.js then:

Using .env.environmentName files is a common way to provide environment specific data.

The cors middleware will accept an array of allowed origins for the origin configuration option and will compare the Origin header to them and generate the right Access-Control-Allow-Origin header.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM