DEV Community

BillyGoat12
BillyGoat12

Posted on

Cross Origin Request

Cross origin request is when a origin makes a request to a different origin. An origin is a server’s hostname. A origin consist of scheme, domain, and port. So https://www.google.com/routeA and https://www.google.com/rounteB are the same origin but are at different route but if anything before the route was different in the URL then that would make it a different origin.

Alt Text

Before we can go into making a request to another origin we will have to talk about the same origin policy. Same origin policy is something your web browser enforces that says if the origin is not the same then you will not be able to make request to that origin. So when we are trying to access resources from a different origin we will need to bypass this policy. Also the same origin policy is something your browser enforces and not your server but your server can enhance the it.

Alt Text

How can we get around this? Well there are several methods you can use to get around this actually but today we will be talking about just one way. So the biggest thing here is having a header that says access-control-allow-origin. One way you can accomplish this is through a proxy. The Access-Control-Allow-Origin is a response header that determines whether the response can be shared with requesting code from the given origin. The literal value "*" tells browsers to allow requesting code from any origin to access the resource.

Alt Text

Servers are not under the same origin policy rule, they can request data from any other server. What we can do here is have a middle man to make the request for us and the middle man will be the server. We will be asking the server to make a request for us and send us back the response and this is known as a proxy. There is an API called CORS-anywhere and it basically is a proxy that will add the header that says access-control-allow-origin.

Alt Text

How to use a proxy? well using a proxy is really easy and all you have to do is add the proxy URL before the URL of the origin of whom you wish to make the request to in your request function.

Alt Text

In conclusion using a proxy is one of the best ways to bypass the same origin policy because a request we made that goes out, goes through the proxy and will not send my cookies or anything specific to that website. When your browser is making a request out to specific website and if your browser has set cookies in your browser, when the request goes out it will send those cookies with it. So if you made a request out to Facebook then your cookie data will also go with it but if you use a proxy you will be able to protect this data.

Top comments (0)