Cross-Origin Resource Sharing (CORS) is a security feature implemented by web browsers that controls how resources on a web server can be requested from another domain. It's a crucial mechanism for managing cross-origin requests and ensuring secure interactions between different origins on the web.

Cross origin request from the browser

Screenshot 2024-08-31 at 7.36.42 PM.png

Same request from Postman

Screenshot 2024-08-31 at 7.37.08 PM.png

Real world example

Create an HTTP Server

const express = require("express");

const app = express();

app.get("/sum", function(req, res) {
    console.log(req.name);
    const a = parseInt(req.query.a);
    const b = parseInt(req.query.b);

    res.json({
        ans: a + b
    })
});

app.listen(3000);
<!DOCTYPE html>
<html>

<head>
  <script src="<https://cdnjs.cloudflare.com/ajax/libs/axios/1.7.6/axios.min.js>"></script>
</head>

<body>
  <div id="posts"></div>
  <script>
    async function sendRequest() {
      const res = await axios.get("<http://localhost:3000/sum?a=1&b=2>");
    }

    sendRequest();
  </script>
</body>

</html>
cd public
npx serve

Screenshot 2024-08-31 at 7.40.59 PM.png

<aside> 💡

You will notice the cross origin request fails

</aside>

npm i cors