skip to Main Content

I’ve created a react app that runs on port:3000 and an express app that runs on port:3001.
I am using express-session and connect-mongo to handle user sessions. When I set a user session in /login it was recorded in MongoDB as expected. But when I query for req.session.user later in a different path/route, for example /channels it returns undefined.

This is how my app.js looks

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const {Server} = require("socket.io");
const io = new Server(server);
const port = process.env.PORT || 3001;
const cors = require("cors");
const path = require('path');
const session = require('express-session');
const bodyParser = require('body-parser');
const oneDay = 1000 * 60 * 60 * 24;
const MongoStore = require('connect-mongo');
const md5 = require('md5');
const hash = '=:>q(g,JhR`CK|acXbsDd*pR{/x7?~0o%?9|]AZW[p:VZ(hR%$A5ep ib.&BLo]g';

app.use(session({
    secret: hash,
    saveUninitialized: false,
    resave: false,
    store: MongoStore.create({
        mongoUrl: 'mongodb://localhost:27017/chat',
        ttl: 14 * 24 * 60 * 60 // = 14 days. Default
    })
}));

app.use(
    cors({
        origin: true,
        credentials: true,
        optionsSuccessStatus: 200
    }));

// create application/json parser
const jsonParser = bodyParser.json({limit: '50mb'})

// create application/x-www-form-urlencoded parser
const urlencodedParser = bodyParser.urlencoded({limit: '50mb', extended: false})

app.post('/login', jsonParser, (req, res) => {
    db.users.find({email: req.body.email}).toArray().then(user => {
        if (user.length < 1) {
            res.send({success: false, error: 'NOT_FOUND', message: 'Invalid login info!'});
        } else {
            user = user[0];
            if (user.password === req.body.password) {
                db.users.updateOne({"email": user.email}, {$set: {"online": "1"}}).then(ret => {
                    req.session.user = user.email;
                    req.session.userdata = user;
                    res.json(<=user data=>);
                });
            }
        }
    })
});

app.post('/channels', async (req, res) => {
    if (!req.session.user) {// THIS IS ALWAYS TRUE; EVEN AFTER SUCCESSFUL LOGIN
        res.json({logout: true});
        return;
    }
    const user = JSON.parse(req.session.userdata);
    const channels = db.channels.find({contacts: {$all: [user._id]}}).toArray().then(channels => {
        let allch = {};
        channels.map(function (channel) {
            channel.id = channel._id.toString();
            channel.notif = 0;
            allch[channel.id] = channel;
        });
        res.json(allch);
    });
});

2

Answers


  1. I think you will need to call req.session.save() yourself when you want to update the session store with the current data.

    Login or Signup to reply.
  2. When You fetch from front-end for specific route, don’t forget to include in options: "credentials: "include" ", like here:

    const options = {
      method: "POST",
      headers: {
        "content-type": "application/json",
      },
      body: JSON.stringify(searchInput),
      credentials: "include",
    };
    
    fetch("http://localhost:4000/sendSearchInput", options)
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
      });
    

    Edit:
    Note – This should be included in each request from the client that either sets or reads the ‘express-session’ middleware (req.session.x).
    (Not just reads)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search