I have a frontend setup with react and a back-end made with express and mongodb, I have a component which needs to make a fetch request including the credentials with should be already set. All of the routes work on postman but I'm not able to recreate the functionality with the fetch function.
Express server:
...
server.use(helmet());
server.use(compression());
server.use(cors({
credentials: true,
}));
if (process.env.NODE_ENV !== "production") {
server.use(logger("dev"));
}
server.use(express.json());
server.use(express.urlencoded({ extended: false }));
server.use(cookieParser());
server.use(
session({
secret: process.env.COOKIE_SECRET,
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
);
server.use(auth.initialize);
server.use(auth.session);
server.use(auth.setUser);
//API ROUTES
server.use("/user", require("./api/routes/user"));
server.use("/pitch", require("./api/routes/pitch"));
server.use("/match", require("./api/routes/matchmaking"));
...
User routes:
router.post("/login", passport.authenticate("local"), (req, res, next) => {
return res.status(200).json({
message: "User logged in correctly",
redirect: "/"
});
});
router.get("/checklogin", (req, res, next) => {
if (req.user) return next();
else
return res.status(401).json({
error: "User not authenticated"
});
},
(req, res, next) => {
return res.status(200).json({
message: "User logged in correctly",
redirect: "/"
});
});
Frontend:
useEffect(() => {
async function fetchData() {
const response = await fetch("http://localhost:8000/user/checklogin", {
credentials: 'include'
});
const data = await response.json();
console.log(data);
}
fetchData();
}, []);
Using this code I get this error
Access to fetch at 'http://localhost:8000/user/checklogin' from origin 'http://localhost:3000' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
As I said prior everything works on postman but not with the fetch function.
As the error says:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
When you do this server.use(cors()), all of the requests are allowed by default and because of which, the 'Access-Control-Allow-Origin' header is set to '*'.
So, you might want to specify the corsOptions to get around this issue.
var whitelist = ['http://localhost:3000', /** other domains if any */ ]
var corsOptions = {
credentials: true,
origin: function(origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
}
server.use(cors(corsOptions));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With