How CORS (Cross-Origin Resource Sharing) Works?

Written by dipakkr | Published 2019/12/18
Tech Story Tags: react | cors | javascript | nodejs | developer | angular | programming | coding

TLDRvia the TL;DR App

If you are a web developer, you must have seen the ‘CORS’ error appearing often on your screen when you try to call the API. But, Why does it happen?
Well, For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts. For example, if you want to access your API hosted at `
https://api.github.com
 from your client-side frontend application which is hosted at 
https://example.com
. The browser will not allow this request to complete.
You only need to think about CORS when :
  1. API accessed by the browser.
  2. API is hosted on a separate domain.
So, why does it happens?
The browsers enforce a security feature called Same Origin Policy. According to Same Origin Policy, the Same Origin calls are allowed and Different Origin calls are not allowed.
Uhh !! What is this Same Origin, Different Origin? Let’s see this more in detail. Browsers define the Origin as a combination of Scheme, Host, and Port.
1. Scheme name — It is the protocol to be used to access the resource on the Internet. The scheme names followed by the three characters :// .The most commonly used protocols are 
http://
https://
ftp://
, and 
mailto://
.
2. Hostname — It is the address of the host where the resource is located. A hostname is a domain name assigned to a host computer. This is usually a combination of the host’s local name with its parent domain’s name. For example, 
www.hackernoon.com 
consists of the host's machine name 
www
 and the domain name `hackernoon.com`.
3. Port Number — Port is a communication endpoint where your application run. For more information about Port Number. Check out this Link.
If these three combinations of Scheme, Host name, and Port are same then the browser identifies it as the Same Origin. And, the request gets complete.
So, Does it means that it is impossible to make Cross-Origin HTTP request ??
The answer is NO.
That's where the CORS comes into picture, Cross-Origin Resource Sharing mechanism.

How CORS Works

CORS allows the server to explicitly whitelist certain origin and help to bypass the same-origin policy.
If your server is configured for CORS, it will return an extra header with “Access-Control-Allow-Origin” on each response.
For example, if my API server hosted at 
https://api.dipakkr.com/
is CORS configured and I am making a request from my client application 
https://github.com
 to fetch some data. The response will have this header.
Access-Control-Allow-Origin: https://github.com

CORS Preflight Request

Preflighted requests first send an HTTP request by the OPTIONS method to the resource on the other domain, to determine if the actual request is safe to send or not.
You can read more about CORS Preflight request at MDN or check out this video by Akshay Saini.

How to Enable CORS

For enabling CORS on your server application. You need two things.
  1. First, you need to determine the origins to whitelist.
  2. Second, you have to add the CORS middleware to the server.
Here, I am explaining to you the steps to configure CORS on your NodeJS server.
First install the 
cors 
npm package from this link.
npm install cors
Then go to your server application and add the below code.
// require the cors package
var cors = require('cors');

// enables cors
app.use(
  cors({
    origin: "*",
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    preflightContinue: false
  })
);
Here you can see I am using origin: "*" which means any domain can access this application.
To know more about CORS, please visit MDN.
Don’t forget to give your feedback in the comments. Getting feedback helps me improve.
I write about new stuff almost daily. You can follow me on Twitter | Instagram
Cheers!

Published by HackerNoon on 2019/12/18