CORS Tutorial in Depth | Complete Guide

pitfalls and security OG

In this blog, I will cover CORS Tutorial in Depth by considering various examples. You will learn how to resolve the various errors that you usually get in the browser. CORS stands for Cross-Origin Resource Sharing. It is a feature that relaxes the security of your Website or API. By Default, the same-origin policy applies in all the browsers so you call from origin back to your web server. CORS allows certain origins that are allowed to access the API so if you have got certain subdomains or a particular 3rd Pary Website then you can allow just those rather than everyone.

cors tutorial

It does this by returning the header in the response header. If you try to access this from the command line then you will be able to do so because it is just a browser security feature. You can Play around with cors in Test Cors or use the below node code.

res.setHeader('Access-Control-Allow-Origin', <Origin>);
res.setHeader('Access-Control-Allow-Methods', <Method>);
res.setHeader('Access-Control-Allow-Headers', <Headers>);
res.setHeader('Access-Control-Allow-Credentials', <Boolean Credentials>);

Consider we have two different origins and they want to share resources. Before the actual API call, a Preflight(OPTIONS) call will be made at the server so that server can verify if the current request is allowed or not. If the current request is allowed then in response It set an additional HTTP header along with the request and send back to the client browser. Once the browser receives then actual API call is made. If the verification fails then it block and throw error.

cors tutorial

Let’s Consider Different Scenario of CORS Error

  • Allowed only Particular Origin.

If a client tries to access from another origin that is not mentioned in ‘Access-Control-Allow-Origin’ then you will get a cors error. In Below Example only allowed origin is ‘abc.com’.

const express                   = require('express');
const bodyParser                = require('body-parser');
const cors                      = require('cors');

let app     = express();
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'https://abc.com');
  next();
});

app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(bodyParser.json({limit: '50mb'}));
app.get('/ping',(req,res)=>res.send("OK"));
app.listen(3000);

If we try to access from another origin then we will get a cors error(Access to fetch at 'http://localhost:3000/ping' from origin 'https://infohubblog.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header has a value 'https://infohubblogi.com' that is not equal to the supplied origin. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.) If you want to allow all origin then you can pass * to allow all domain and subdomain.

cors tutorial

When We try to access API from infohubblog.com and in the below code if we mention allowed origin as infohubblog.com then you will not get Cors Error.

const express                   = require('express');
const bodyParser                = require('body-parser');
const cors                      = require('cors');

let app     = express();
app.use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', 'https://infohubblog.com');
  next();
});

app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(bodyParser.json({limit: '50mb'}));
app.get('/ping',(req,res)=>res.send("OK"));
app.listen(3000);
Screenshot 2021 09 18 at 3.32.22 PM

  • Allowed only Particular Method
  • If the Client tries to access another method that is not mentioned in the “Access-Control-Allow-Methods” then you will get an error. By Default It will not give errors in GET and POST. Below example, I have created a PUT API and have not mentioned methods in “Access-Control-Allow-Methods”. If we try to hit ping API then we will get an Error.

    const express                   = require('express');
    const bodyParser                = require('body-parser');
    const cors                      = require('cors');
    
    let app     = express();
    app.use(function (req, res, next) {
      res.setHeader('Access-Control-Allow-Origin', 'https://infohubblog.com');
      res.setHeader('Access-Control-Allow-Methods', 'GET,HEAD,POST');
      next();
    });
    
    app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
    app.use(bodyParser.json({limit: '50mb'}));
    app.delete('/ping',(req,res)=>res.send("OK"));
    app.listen(3000);
    cors tutorial

    Conclusion

    In order to resolve the error, your domain and methods need to be allowed from the server domain. If you are facing any issues then please let us know in the comment section.

    Hope You Like our “CORS Tutorial in Depth” Blog. Please subscribe to our blog for the latest upcoming blogs on emails.

    Happy Coding!

    Read More: Javascript Promises in Depth | Complete Guide, Latest ECMAScript 2021 / ES12 | Feature in Javascript

    Be the first to comment on "CORS Tutorial in Depth | Complete Guide"

    Leave a comment

    Your email address will not be published.


    *