Fixing CORS policy example (React/Golang)
Cross-origin resource sharing (CORS) is a standard mechanism that allows JavaScript XMLHttpRequest (XHR) calls executed in a web page to interact with resources from non-origin domains. CORS is a commonly implemented solution to the same-origin policy that is enforced by all browsers.
Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.
It's often can git fixed with a proxy server (CORS Proxy). We can run a proxy server on the address that we want to send our HTTP requests to. CORS Proxy allows us to bypass CORS errors using a proxy server that acts as a bridge between the client and the server. So, instead of requesting the target server, it sends the request to the proxy server instead.
Let's create a HTTP server with Golang that has the following endpoints and runs on localhost:8080
.
cd api
go build . -o ./main
./main
You can also set the program flags.
Flag | Description | Default |
---|---|---|
port |
Api port | 8080 |
mongo |
MongoDB URI | mongodb://127.0.0.1:27017/ |
database |
MongoDB database name | cors |
Now let's create a React application that runs on localhost:3000
.
cd application
npm start