I have made an API(using expressjs) and frontend with react the API runs on localhost:5000 and React frontend on localhost:3000 , I dont know why am I getting this err in my chrome console when I try to make a request to my backend using axios This is the err
Access to XMLHttpRequest at 'http://localhost:5000/getme' 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I have applies cors policy on the backend
relevant backend code
app.use(cors());
app.get("/getme", authMiddleware.protect, (req, res, next) => {
res.status(200).json({
status: "success",
user: req.loggedInUser,
});
});
code for authMiddleware.protect function (which is obviously on backend)
module.exports.protect = async (req, res, next) => {
const cookie = req.cookies;
let token;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer")
) {
token = req.headers.authorization.split(" ")[1];
} else if (req.cookies.token) {
token = req.cookies.token;
}
if (!token) {
// tell them to login
console.log("no token");
return res.status(403).json({
status: "action",
redirect: "login",
});
// return next();
}
try {
// verify token
const _id = jwt.verify(token, process.env.JWT_SECRET)._id;
// find User
const loggedInUser = await networking.findDoc(User, { _id });
if (!loggedInUser) {
// this is rare to occur
return res.status(404).json({
status: "action",
redirect: "signup",
});
}
req.loggedInUser = loggedInUser;
// console.log("logged in user:", loggedInUser);
return next();
} catch (err) {
// invalid signature, (handle this trivial case on backend)
if (err.message === "invalid signature") {
console.log("malformed"); //test again
return res.redirect("/logout");
}
return next(new Error(`err in protector: ${err.message}`));
}
};
now from frontend I am sending a get request to this getme route and I am sending token via cookies
here is my frontend axios code , the { withCredentials: true } option is set to true because I want axios to send my cookie to backend
const getUserUrl = http://localhost:5000/getme
export const getLoggedInUser = async () => {
try {
console.log(">>url:", getUserUrl);
const { data } = await axios.get(getUserUrl, { withCredentials: true });
console.log("data>>", data);
debugger;
if (data.success) {
return data.user;
} else {
alert("some err getting user");
return;
}
} catch (err) {
console.log("err>>>", err.message);
alert("err in axio");
}
};