XMLHttpRequest has been blocked by CORS policy:
Ashwani Singh

Ashwani Singh @imashwani

About: Software developer

Location:
India
Joined:
Feb 5, 2024

XMLHttpRequest has been blocked by CORS policy:

Publish Date: Mar 2
7 1

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

Comments 1 total

Add comment