App.js
const express = require("express");
const Mongo_connect = require("./mongo-config.js");
const cors = require("cors");
const router = require("./src/Router/route");
const mongoose = require("mongoose");
const session = require("express-session");
// const session = require("express-session");
const MongoStore = require("connect-mongo");
const app = express();
const mongo = async () => {
await Mongo_connect(app);
};
mongo();
const corsOptions = {
origin: "http://localhost:5173",
credentials: true,
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(express.static("../../Frontend/home/dist"));
// Remove this later
app.use("/api/v1/", router);
app.listen(3600, () => {
console.log("Server listening to port 3600, ENJOY");
});
app.get("/info", (req, res) => {
console.log(req.session);
});
module.exports = mongoose.model("User");
module.exports=app;
Mongoconfig.js
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const express = require("express");
const cookieParser = require("cookie-parser");
const Mongo_connect = async (app) => {
const uri =
"#############################################";
mongoose.connect(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const db = await mongoose.connection;
db.on("error", console.error.bind(console, "Connection error:"));
db.once("open", () => {
console.log("Connected to MongoDB...");
const sessioninit = async () => {
const sessionCollection = await mongoose.connection.db.collection(
"sessions"
);
const mongoStore = await MongoStore.create({
mongoUrl:
"############################################",
collection: sessionCollection,
});
console.log("Mongostore intitalization done...");
const oneDay = 1000 * 60 * 60 * 24;
await app.use(
session({
secret: "070703",
resave: true,
saveUninitialized: true,
store: mongoStore,
// cookie: {
// maxAge: oneDay,
// secure: true,
// },
})
);
app.use(cookieParser());
};
sessioninit();
console.log("Session created successfully...");
});
};
module.exports = Mongo_connect;
Main issue is the req.session object is undefined even after its initalization
Whenever I try to set properties of req.session this error is obtained.
TypeError: Cannot set properties of undefined (setting 'username')
other key points are:
- Mongo connection is successfully established (I can store and retrieve data from the DB)
- Session collection is being successfully created in the DB.
- I don't think the session object is properly initialized.