DEV Community

Ashwani Singh
Ashwani Singh

Posted on

2 1 1 1 1

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

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (1)

Collapse
 
deathcrafter profile image
Shaktijeet Sahoo
Comment hidden by post author

Some comments have been hidden by the post's author - find out more

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

If this article connected with you, consider tapping ❤️ or leaving a brief comment to share your thoughts!

Okay