HTTP Cross origin resource sharing

In this tutorial, we will discuss Cross-origin resource sharing. In the modern world with the rapid changes in technology and the way we interact not just with people, but the interaction of two applications has also evolved. With the increased use of JavaScript and TypeScript, we have to establish communication between two more applications. But modern browser’s same-origin policy limits one application to make an HTTP request to a different origin.

What is the same-origin policy?

As per wiki In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin.

Cross-Origin Resource Sharing enables web clients to make HTTP requests to servers hosted on different origins. CORS is a unique web technology in that it has both a server-side and a client-side component. The server-side component configures which types of cross-origin requests are allowed, while the client-side component controls how cross-origin requests are made.

CORS is a unique web technology in that it has both a server-side and a client-side component. The server-side component configures which types of cross-origin requests are allowed, while the client-side component controls how cross-origin requests are made.

So if the browsers enforce the same-origin policy, how does CORS work? The magic lies in the request and response headers. The browser and the server use HTTP headers to communicate how cross-origin requests should behave. Using the response headers, the server can indicate which clients can access the API, which HTTP methods or HTTP headers are allowed, and whether cookies are allowed in the request.

We can break down the steps to process a CORS request and response as follows.

  1. The CORS request is initiated.
  2. The browser includes additional HTTP headers on the request before sending the request to the server.
  3. The server includes HTTP headers in the response that indicates whether the request is allowed.
  4. If the request is allowed, the browser sends the response to the client code.

If the headers returned by the server don’t exist or aren’t what the browser expects, the response is rejected and the client can’t view the response.

Let’s create a simple example to call two different APIs using JQuery and see the response.

 
<html>
<head> 
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js" ></script>
<script type="text/javascript">
let url ='http://worldtimeapi.org/api/timezone/asia/kolkata.txt';
//let url ='https://in.yahoo.com/';
$.ajax({
  url: url,
   success: function(data){
      $('#data').html(data);
   }
});
</script>
</head>
<body>
<p>Date Time detail for</p>
<span id="data"></span>
<p id="datetime"> </p>
</body> 
</html>
 

Save the above code in an HTML file and run it in chrome. When we use the World Time API as a URL for our get request, it is executed successfully and we can see the detailed response in the browser as below.

Success CORS

But, if we comment on the world time API URL and remove comments from the yahoo URL and re-run the file, we wouldn’t see any response in the browser. If you check the browser console you will see an error message with details as :

“Access to XMLHttpRequest at ‘https://in.yahoo.com/’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

Fail CORS

Here you can see the world time API application allowing a request from a different origin but yahoo did not.

Happy Learning !!

HTTP Request Methods and specification

HTTP defines a set of request methods to specify the desired action to be performed for a given resource. These request methods are sometimes referred to as HTTP verbs. Each of them implements a different semantic, but some common features are shared by a group of them: e.g. a request method can be safe, idempotent, or cacheable.

Http Request Method

Use Request Methods to map CRUD (create, retrieve, update, delete) operations to HTTP requests.

Method DescriptionExample
GETGET is used to Retrieve information. GET requests must be safe and idempotent, meaning regardless of how many times it repeats with the same parameters, the results has to be same.Retrieve an Employee with an ID of 1:
GET /employee/1
POSTThe POST method is used to submit an entity to the specified resource, often used to create a new entity, but it can also be used to update an entity.Create a new Employee:
POST /addresses
PUTThe PUT method replaces all current representations of the target resource with the request payload and it is idempotent.
Idempotency is the main difference between PUT versus a POST request.
Modify the Employee with an ID 1:
PUT /addresses/1
DELETEThe DELETE method delete the specified resource. Delete an employee having ID 1:
DELETE /addresses/1
OPTIONSThe OPTIONS method is used to describe the communication options for the target resource.
PATCHThe PATCH method Update only the specified fields of an entity at a URI. A PATCH request is also idempotent.PATCH /addresses/1

Specifications
RFC 7231, section 4: Request methods Specifies GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE.

RFC 5789, section 2: Patch method Specifies PATCH.

Recommended Read
Rest Web Services

Happy Learning !!