Trusted answers to developer questions

How CORS (cross-origin resource sharing) works

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

If you are a web developer, you must have seen the CORS error appear on your screen when you try to call the API, but why does that happen?

widget

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 that 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.
widget

So, why does this happen?

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 in more detail. Browsers define the Origin as a combination of Scheme, Host, and Port.

  • Scheme name- It is the protocol to be used to access the resource on the Internet. The scheme names are followed by the three characters :// .The most commonly used protocols are http://, https://, ftp://, and mailto://.
  • 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.dev.to consists of the host’s machine name www and the domain name dev.to
  • Port Number - Port is a communication endpoint where your application is run. For more information about Port Number, check out this link.

If these three combinations of Scheme, Hostname, and Port are the same, then the browser identifies it as the Same Origin and the request gets completed.

Does this mean that it is impossible to make the Cross-Origin HTTP request??

The answer is NO; that’s where the CORS comes into the picture.

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/users is CORS configured, and I am making a request from my client application https://github.com to fetch some data, then t​he response will have this header.

Access-Control-Allow-Origin: https://educative.io
widget

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.

How to Enable CORS

To enable CORS on your server application, you need two things:

  1. First, you need to determine the origins of whitelist.
  2. Second, you have to add the CORS middleware to the server.

Below, I will explain the steps of how 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.

Please note that it is dangerous to put origin:"*" in a production application (you should never do that). Instead, specify the domains you want to whitelist.

To know more about CORS, please visit MDN. It’s a great place for web developers.

I write about new things almost daily; you can follow me on Twitter | Instagram

If you liked the post, give some ❤️!! Cheers

written by Deepak Kumar

RELATED TAGS

javascript
node
Attributions:
  1. undefined by undefined
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?