DEV Community

Ashwani Singh
Ashwani Singh

Posted on

XMLHttpRequest has been blocked by CORS policy:

Error
"Access to XMLHttpRequest at 'http://localhost:5001/auth/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Solutions

This error occurs because your backend server (localhost:5001) is not allowing requests from your frontend (localhost:3000) due to CORS (Cross-Origin Resource Sharing) policy restrictions. To fix this, you need to configure your backend to allow requests from your frontend.

Fix for Node.js (Express) Backend

If you're using Express.js, install the cors package and configure it:

1. Install cors

Run this command in your backend project:

npm install cors

Enter fullscreen mode Exit fullscreen mode

2. Update Your Backend Code

Modify your Express server code (index.js or server.js):

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

const app = express();

// Allow requests from frontend (localhost:3000)
app.use(cors({
    origin: "http://localhost:3000",
    methods: ["GET", "POST", "PUT", "DELETE"],
    allowedHeaders: ["Content-Type", "Authorization"]
}));

app.use(express.json());

// Your routes here...
app.post("/auth/register", (req, res) => {
    res.json({ message: "User registered successfully" });
});

app.listen(5001, () => {
    console.log("Server running on port 5001");
});

Enter fullscreen mode Exit fullscreen mode

Alternative: Enable CORS for All Origins (Temporary)

For debugging purposes, you can allow all origins:

app.use(cors());

Enter fullscreen mode Exit fullscreen mode

If Using Fetch in Frontend

Make sure your fetch request in React includes mode: 'cors':

fetch("http://localhost:5001/auth/register", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({ username: "ashwani", password: "123456" }),
    mode: "cors"
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error("Error:", error));

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
deathcrafter profile image
Shaktijeet Sahoo

If you want to write an article about an error, then at least give a brief background of the reason. I don't know what "cors" is, what makes it important, and I will do app.use(cors()) to just solve a single request error and open my app to vulnerabilities I am unaware of.

And do not post stuff like this unless you have something new to say that isn't already on Stack.