How to fix cross-free errors-cORS defects described

by SkillAiNest

In this article, you will learn about an important concept: Cross Oregon Resources Sharing Policy. As a developer, you may face a situation where the client’s request from the server fails, and the browser show a red error as “CORS policy failed.” Even when the application is properly implemented, this error can occur.

Some initial people can find online or copy temporary improvements, which can solve this problem without providing real understanding. Here, we will break the CORs clearly so that you can understand why this happens and how to fix it.

CORS error

Here’s what we will cover

Provisions

To go beyond this guide and to take the most of your you, you should be:

  1. The basic knowledge of Javascript – you should be familiar with Javascript syntax, functions, and recovery API to make HTTP applications by the client.

  2. node.js and npm Install-you will use node dot j for server side setup and npm To manage packages. You can download from node.js Here.

  3. A Code Editor (such as VS code) – you will need the code editor like Vs. code To write and run your client and server files.

  4. The basic knowledge of HTTP methods – Gate, Post, Put, Knowledge of requests will help you understand how the browser and server communicate.

  5. A browser that has developer tools – chrome, firefox, or developer tools.

  6. Optional but helper: Vs. Live Server Extension-This helps to run your HTML files locally to test client server requests.

I have also produced a video to go with this article. If you like the type of video as well as learning from the text, you can check it here:

https://www.youtube.com/watch?v=ryvgbomv8ng

Project Setup

Before searching for Cors, let’s set a basic client and server.

Start the server

First, make a project folder whose name is cors-tutorialAnd inside the folder, make another folder called server. Then, I get navigated server Start the folder and node project. Run the command one by one:

mkdir cors-tutorial
cd cors-tutorial
mkdir server
cd server
npm init -y

Install the desired package

The basic server setup L you, you will use a famous node Dot JS Framework, Express. JS. Install it with the following command:

npm install express

Create a server file

A server/app.js Inside the file file, import the installed express package and start the app using express() Event then, make a way /data It returns a simple JSON object.


const express = require("express");
const app = express();

app.get("/data", (req, res) => {
    res.json({
        name: "Bangladesh",
        description: "Land of emotions",
    });
});

app.listen(3000, () => {
    console.log("Server is running on http://localhost:3000");
});

Drive the server

Start with the following command to the server:

node app.js

Client Setup

It’s time to set up a client. Make a index.html And script.js File within cors-tutorial Folder


html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>What is CORStitle>
  head>
  <body>
    <div>
      <button onclick="fetchData()">Fetch Databutton>
    div>

    <script src="./script.js">script>
  body>
html>

async function fetchData() {
  const response = await fetch("http://localhost:3000/data", {
    method: "GET",
  });

  const data = await response.json();
  console.log(data);
}

Demonstration: Client Server interactions

Client side

  • index.html Is labeled on the same button Fetch Data.

  • The mock runs 127.0.0.1:5500 VS code directly using the server.

  • The browser console is open to see the logs.

Server side

  • Is in a minimum express server server Folder

  • app.js Consists of /data Root that looted:

      {
        "name": "Bangladesh",
        "description": "Land of emotions"
      }
    
  • The server is running localhost:3000

How does it work

  • Click Recover the data Button calls fetchData() By script.js.

  • fetchData() The server sends a gate request and logs the JSON response.

  • To see directly localhost:3000/data Json also shows output.

  • Since the client and the server ports are different, you may see a corrus -related error message in the console.

Access-Control-Aleo-Norn Corps Error

Note

  • In the same way, PHP or other backward languages ​​can be used to make APIs.

  • The demonstration shows how the client interacts with the server before handling the CORS problems.

What is the original?

The original means the means from which the request is coming from. I requested 127.0.0.1:5500 And I’m trying to access the data localhost:3000. Both are URL but they are different, okay? When we say that URL we mean the domain part, not the whole path. localhost And 127.0.0.1 Looks alike, but as far as the origin is concerned, they are different. The ports are also different. Because of this, the URL or the origin is considered different.

So the source and the servers are different, and that’s why it says that “the COS has been blocked by policy” and “no” is available on the desired resources to control access. When someone looks at this early, they cannot understand the whole process: why this happens and how it happens. We will learn how to solve it now.

What does a browser mean with a carry policy?

Just imagine that your website xyz.com And this is our front. And is your server www.abc.comA different domain, these are both different domains. We expect xyz.com To request abc.com And abc.com To send the answer – easy.

Request - the concept of response

The code we have written should work, but sometimes it doesn’t happen, which can be confused. Why does this happen? The reason is simple: COC policy is preventing application. The COC policy is a browser policy. Its full shape is Cross-Noorgain Resource Sharing (CORS).

Cross Oregon Resources Sharing (CORS)

In simple terms, if the applicant’s domain is different from the recipient’s domain, then as a default, browser will reject the application. Although it may reach the server, the browser will refuse to respond to the client. That is why we see this behavior.

How to fix CORS policy errors

This task needs to be handled to the server. First, open the browser network tab. When you request, reload and clean, then click fetchData. See the details of the request. Each application has two parts: Apply the header and the response header.

The application header is sent by browser and includes metadata and browser information. Response headers are manufactured by the server and also contains metadata, while the application header is made by client (browser).

If you inspect the response, the error says: “No ‘access control Al -Worne’ header is on the desired resources”. So you need to find this header in response. In the network tab, if you check the response header, you’ll see that there is no Access-Control-Allow-Origin. If there was a header in response, the browser would allow access. So you have to add the appropriate header in response.

Missing Access Control-Aloo Header

So what should we do? If you want to fix it in the Node Dot JS/Express setup, go to it app.js I file server Stop and install the folder server cors Package:

npm install cors

After installing the package, restart the server. Import the next package and ask the app to use. cors() Function can accept AN origin Option If we set origin to localhost:5500Which is the URL of our client, the server will only allow it. If you want to allow multiple reality, you can pass a URL array. Here, I am setting the same URL as the client runs at Port 5500. This means that requests will not be allowed from the other address.

Now you can reload, clean the console and click fetchData Once again, but you still have a problem. Why? Because client was using URL 127.0.0.1 Instead of localhost. It is a change, and the origin should be quite similar. So you can change it 127.0.0.1:5500 In the server conference.

Now you can reload, clean and click fetchData. Everything should now work as expected: there is no mistake sent, and the data console was printed.

If you inspect Network Response Headers for data application, you should see Access-Control-Allow-Origin: http://127.0.0.1:5500. This means that the server responded with the Cars Header and allowed it to origin. Since the actual match, the application was successful. TAXEWEEL: must include one in the server Access-Control-Allow-Origin Explaining the Domain permitted by the header. If you want to allow every original (for public API) you can use *. In the express, you can easily call app.use(cors()) To allow all the original. This will allow the server to accept the requests from any original.


const express = require("express");
const cors = require("cors");
const app = express();


app.use(cors({ origin: " }));

app.put("/data", (req, res) => {
    res.json({
        name: "Bangladesh",
        description: "Land of emotions",
    });
});

app.listen(3000, () => {
    console.log("Server is running on http://localhost:3000");
});

This ensures that the server clearly allows the client’s origin, which resolves CORS policy errors.

Additional notes on CORS

Another thing to note. The request we were sending to the client was a gate application. To get, post, delete, the process is straightforward. But for methods such as Pitt, which edit the data on the server, CORS behaves slightly different. If you change the client’s request to send a pet request and the server describes one app.put Route, you will see two requests in the network panel. The browser first sends a prefix request. This is a browser way to check whether it is allowed to send the original request. This preflite application is a OPTIONS Application automatically sent by the browser before the original PUT request.


const express = require("express");
const cors = require("cors");

const app = express();
app.use(
    cors({
        origin: ",
        methods: ("GET", "POST"),
    })
);

app.put("/data", (req, res) => {
    res.json({
        name: "Bangladesh",
        description: "Land of emotions",
    });
});

app.listen(3000);

async function fetchData() {
    const response = await fetch("http://localhost:3000/data", {
        method: "PUT",
    });

    const data = await response.json();

    console.log(data);
}

When you look at a pre -light request in the network tab, you will see the Response Header that includes Access-Control-Allow-Methods And the other Cors Header. Default. cors Allows all methods such as the package GETFor, for, for,. POSTFor, for, for,. PUTFor, for, for,. HEADFor, for, for,. PATCHAnd so on. If you want strict security, you can explain the methods allowed in CORS order. Set, for example, methods Option ('GET', 'POST') Not only allowing and posting and deleting and deleting to post only. Even if the original is similar, if the procedure is not allowed, the prefix will fail and the original application will be blocked.

Example of preferred application

If you perform the same application in a permitted way, it will fail. The console will show the correct CORS error message. Now when you understand the flow, you will be able to explain in an interview:
“URL-2 access (URL-2) has been blocked by CORS policy: PUT procedures are not allowed by control-al-Matheuds access to preflight response.” Pre -Light Check Ara Access-Control-Allow-Methods: GET, POST And therefore blocked the PUT application.

So you can control the CORS behavior using two important things: Access-Control-Allow-Origin And Access-Control-Allow-Methods. If you understand them and create them on the server, you can control what origin and methods are allowed. This is finally the CORS policy: a browser -enacted security measure. The browser enforce this standard sample so that if the server does not send the appropriate header, the browser will not allow the client to access the answer.

Abstract

The last words

You can find all the Source Code for this tutorial This gut hub repository. If he helped you in any way, consider giving him a star to show his support!

Also, if you have got the information here, share it with others without hesitation that can benefit from it. I will really appreciate your thoughts – mention me on x @Summit_Newsin Or on Facebook @Sumit.ANalyzenFor, for, for,. See my coding lessonOr straightforward Linked to contact me on them.

You may also like

Leave a Comment

At Skillainest, we believe the future belongs to those who embrace AI, upgrade their skills, and stay ahead of the curve.

Get latest news

Subscribe my Newsletter for new blog posts, tips & new photos. Let's stay updated!

@2025 Skillainest.Designed and Developed by Pro