I'm developing my final project and I'm trying to build a MERN project. I'm trying to implement an authentication with passport, and it works in development, but when I deployed I keep getting this error
Access to fetch at 'https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success' from origin 'http://localhost:3000' has been blocked by CORS policy: 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.
But if I manually access the site: https://hospitalveterinariopeninsular.herokuapp.com/api/auth/googleLogin/success', I get the response I need. So I don't know if it's a problem of the server or from React.
This is my code in the server:
Index.js
const app = express();
app.use(
cookieSession({ name: "session", keys: ["whatever"], maxAge: 24 * 60 * 60 * 100 })
);
app.use(passport.initialize());
app.use(passport.session());
dbConnection();
// CORS
app.use(
cors({
origin: process.env.CLIENT_URL,
methods: "GET,POST,PUT,DELETE, PATCH",
credentials: true,
maxAge: 3600,
})
);
app.use(express.static(path.join(__dirname, "/public")));
app.use(express.json());
app.use("/api/auth", authRoutes);
AuthRoutes.js
router.get(
"/google",
passport.authenticate("google", { scope: ["profile", "email"] })
);
// callback from google
router.get(
"/google/callback",
passport.authenticate("google", {
failureRedirect: "/api/auth/googleLogin/failed",
successRedirect: `${process.env.CLIENT_URL}/#/auth`,
})
// googleAuth
);
router.get("/googleLogin/success", (req, res) => {
console.log("success", req.user);
if (req.user) {
res.status(200).json({
success: true,
message: "successfull",
user: req.user,
token: req.user.token,
// cookies: req.cookies
});
}
});
Code from React
export const AuthPage = () => {
useEffect(() => {
const getUser = () => {
fetch(`${process.env.REACT_APP_API_URL}/auth/googleLogin/success`, {
method: "GET",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
})
.then((response) => {
console.log("THIS IS THE RESPONSE", response);
if (response.status === 200) return response.json();
throw new Error("authentication has been failed!");
})
.then((resObject) => {
console.log("POR FAVOR********", resObject);
localStorage.setItem("token", resObject.token);
localStorage.setItem("token-init-date", new Date().getTime());
dispatch(startChecking());
})
.catch((err) => {
console.log(err);
});
};
getUser();
}, []);
return (...);
};
Edit to add github links Backend: https://github.com/JavierGarciaGomez/hvp2021backend Frontend: https://github.com/JavierGarciaGomez/hvp2021frontend
enviromental variables:
React:
REACT_APP_API_URL=https://hospitalveterinariopeninsular.herokuapp.com/api
Node:
PORT=4000
CLIENT_URL=http://localhost:3000
CLIENT_URL_PROD=https://www.hospitalveterinariopeninsular.com