I have a web application that I am building using React on the front end and Node.js on the back end. My API is functioning fine when I make calls using postman, but when I try to make a call using fetch, it fails and I get the error:
"Access to fetch at ‘XXXURL’ from origin ‘http://localhost:5173’ 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. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
First, I tried disabling cors by setting request mode to no-cors in the request options. This didn’t work as the error went away but the request did not go through.
Next, I tried adding the following piece of middle ware to my code:
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "*");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
Same error, nothing changed.
Then, I tried installing cors and using the following code:
app.use(
cors({
origin: ["http://localhost:5173/", "http://127.0.0.1:5173/", "*", null],
})
);
Same error. I have tried several different origins and nothing has worked. I have run out of resources online and am not sure what it could be. I have closed and reopened VSCode multiple times and still nothing. Please help me I am losing it.
Here is my fetch call and api:
Fetch call
async function getFighterStats() {
dispatch({ type: "getFighters/start" });
try {
const requestOptions = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
const res = await fetch(
`http://127.0.0.1:3000/app/v1/fighters/`,
requestOptions
);
const data = await res.json();
dispatch({ type: "getFighters/finish", payload: data });
} catch {
dispatch({
type: "rejected",
payload: "There was an error calling API...",
});
}
}
API
app.js
import express from "express";
import fighterRouter from "./routes/fighterRoutes.js";
import predictionRouter from "./routes/predictionRoutes.js";
import cors from "cors";
const app = express();
app.use(express.json());
app.use(
cors({
origin: ["http://localhost:5173/", "http://127.0.0.1:5173/", "*", null],
})
);
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader("Access-Control-Allow-Origin", "*");
// Request methods you wish to allow
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
// Request headers you wish to allow
res.setHeader(
"Access-Control-Allow-Headers",
"X-Requested-With,content-type"
);
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);
// Pass to next layer of middleware
next();
});
app.use("/app/v1/fighters", fighterRouter);
app.use("/app/v1/prediction", predictionRouter);
export default app;
fighterRoutes.js
import express from "express";
import {
getAllFighters,
addFighter,
getFighter,
checkID,
} from "../controllers/fighterController.js";
const router = express.Router();
router.param("id", checkID);
router.route("/").get(getAllFighters).post(addFighter);
router.route("/:id").get(getFighter);
export default router;
fighterController.js
import fs from "fs";
import { v4 as uuidv4 } from "uuid";
const fighters = JSON.parse(fs.readFileSync(`./data/fighterData.json`));
const checkID = (req, res, next, val) => {
console.log(`fighter ID is: ${val}, it is of type ${typeof val}`);
const results = fighters.find((el) => el.id === val); // REMEMBER TO CHANGE TO el._id
if (!results) {
return res.status(404).json({ status: "fail", message: "Invalid ID" });
}
next();
};
const getAllFighters = (req, res) => {
console.log(fighters);
res.status(200).json({
status: "success",
results: fighters.length,
data: {
fighters,
},
});
};
2
Answers
I removed the cors module and added the following middleware and it worked today
It's basically the same as the other middle ware so maybe my computer was just having issues, but thank you everyone for the help.
I used CORS package in my several projects. And I configured as below.
And make sure you are browsing your React app from
whitelist
.You don’t need to set headers configuration manually. Just comment that code.