amirhnajafiz-presentations / cross-origin-resource-sharing

Internet Engineering presentation: CORS.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Cross-origin Resource Sharing


Fixing CORS policy example (React/Golang)

go version go version version


What is CORS policy?

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.

cors

CORS error

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.

cors error

How to fix it?

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.

proxy


Example

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

About

Internet Engineering presentation: CORS.

License:MIT License


Languages

Language:JavaScript 50.5%Language:Go 27.1%Language:CSS 13.6%Language:HTML 8.8%