my code works but whenever i made a change in the server.js, the req.session.user turns undefined.
This also happens the first time i make a request from the front, i do get authenticate. but right after i dont get the user.name and cookie cause it reads undefined.
if I run it again, it works and it keeps working until i quit the server and start again. it repeats the same pattern, doesnt work first time, then it works.
i believe is related to the backend as any change in the backend gets session.user undefined,
server.js
const express = require("express");
const session = require("express-session");
const app = express();
const mysql = require("mysql2/promise");
app.use(express.json());
app.use(
session({
key: "userId",
secret: "password",
resave: false,
saveUninitialized: false,
cookie: {
expires: 1000 * 60 * 60 * 24,
},
})
);
app.use(
cors({
credentials: true,
origin: ["http://localhost:3000"],
methods: ["GET", "POST"],
})
);
app.post("/login", async (req, res) => {
const { userName, password } = req.body;
try {
const [result] = await db.query(
`select * from user
where
user = ? and
password = ? `,
[userName, password]
);
if (result.length > 0) {
req.session.user = {
loggedIn: true,
user_id: result[0].user_id,
name: result[0].name,
};
res.send(req.session.user);
} else {
res.send({ message: "Wrong password or user" });
}
} catch (error) {
console.error(error);
}
});
// checking whats on the session
app.use((req, res, next) => {
console.log(req.session.user);
next();
});
// session retriving
app.get("/login", (req, res) => {
req.session.user
? res.send({
loggedIn: true,
name: req.session.user.name,
user_id: req.session.user.user_id,
})
: res.send({ loggedIn: false });
});
app.js
Axios.defaults.withCredentials = true;
useEffect(() => {
Axios.get("http://localhost:3001/login").then(({ data }) => {
setUser({
loggedIn: data.loggedIn,
name: data.name,
user_id: data.user_id,
});
console.log(data);
});
}, []);