Ultimate Guide to Understanding CORS

Ultimate Guide to Understanding CORS

CORS

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.

The CORS standard works by adding new HTTP headers which allow servers to serve resources to permitted origin domains. Browsers support these headers and respect the restrictions they establish.

Example: Say your site is example.com and, you have a third-party API at domain another-example.com, which you can access via AJAX.

And let's assume that a page you server from example.com made a request to another-example.com. Normally, user's browser will decline AJAX calls to any other site other than your own domain/subdomain per the Same-Origin Security Policy. But if the browser and the third-party server supports CORS, the following things happen:

  • Browser will send the following HTTP header to another-example.com

     Origin: http://example.com
    
  • If the third-party server, another-example.com, accepts requests from your domain, it will respond with the following HTTP header:

     Access-Control-Allow-Origin: http://example.com
    
  • To allow all domains, third party server can send this header:

     Access-Control-Allow-Origin: *
    
  • If your site is not allowed, browser will throw an error.

    How to Add CORS to a Nodejs Express App

// another-example.com server code

const express = require("express");
const debug = require("debug")("server");

const app = express();
const port = process.env.SERVER_PORT || 3001;

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "https://example.com"); // or use *
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

// API endpoint
app.get("/api/greetings", (req, res) => {
  res.send({
    msg: "Hello there!"
  });
});

app.listen(port, () => debug(`Listening on port ${port}`));

Alternatively, You can also use cors npm package, docs can be found on the link as well.

Now, if example.com made request to this server, browser will allow those requests as this server allows requests originated from example.com.

Did you find this article valuable?

Support Sujeet Agrahari by becoming a sponsor. Any amount is appreciated!