Last Updated: February 25, 2016
·
1.949K
· devtripper

Like a pro: Avoid unneeded application layer using CORS

Almost any browser has the well known same origin policy (http://en.wikipedia.org/wiki/Same_origin_policy). This rule basically restricts script execution to the same host + port.
So, suppose that you have an mvc client side app developed with JS. Probably you will need to talk with some services that are not in the same host. Due to the same origin policy, you wont be able to reach them. So lets discuss to strategies to deal with this issue:

The traditional way

A way to workaround this issue is to call a service (let say, a 'proxy service') that runs on the same host, and let this proxy call the target service.

Picture

So, in example, we have a web app that lists customers somewhere, and a customer web service somewhere else. Then, using the "traditional way", we will need a proxy service that will be used by web app to actually get the data from the customer service. A gangway to customer service, in other words.

The PRO way

As you may guess, the proxy strategy works but looks like a workaround. And it is. And heres where CORS comes into rescue.

Picture

+What is CORS?

Cross-origin resource sharing (http://www.w3.org/TR/cors/) is a web specification that enables the possibility to access cross domain resources. CORS is supported for some browsers, but not all of them. So take care.

+How it works?

Simply checks for the "Origin" request header, that should contain the target host. In response, you will get the "Access-Control-Allow-Origin" header.

+An example?

HTML5Rocks.com site provides plenty of information about CORS. Let me suggest you this example: http://www.html5rocks.com/en/tutorials/cors/?redirect_from_locale=es

Have a fresh tip? Share with Coderwall community!

Post
Post a tip