Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

express-session on saving on routes

I’ve server.js, it is a startup entry point, i declare the session like this

const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const db = require('./database/db');
const session = require('express-session');

const category = require('./category/category');
const threads = require('./threads/threads');
const posts = require('./posts/posts');

const app = express();

app.use(cors({
    origin: 'http://localhost:3000', // replace with your domain
    credentials: true
}));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use(
    session({
        secret: 'bkepcraymanAbcd1234', // Replace with your own secret
        resave: true,
        saveUninitialized: true,
        cookie: { secure: false }
    })
);

// Routes
app.use('/api/category', category);
app.use('/api/threads', threads);
app.use('/api/posts', posts);

in thread.js, i have this method for testing

router.post('/views/:threadId', async (req, res) => {
    try {
        const { threadId } = req.params;
        req.session.test = '123123123123';
        console.log(req.session.test);
        //req.session.viewedThreads = [];
        //req.session.viewedThreads['thread_' + threadId] = true;
        const array = {[threadId]:true};
        req.session.viewedThreads.push(array);

        req.session.save(err => {
            if(err) {
                // handle error
                console.log(err);
            } else {
                // send response
                res.send('Session saved');
            }
        });

i call the /threads/views/16 at first time,
it will log 123123123123,
then i comment out req.session.test = ‘123123123123’;
it will log undefined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

the session not saving the variable, anyone know what is the problem?

>Solution :

Warning The default server-side session storage, MemoryStore

The session data is stored in memory. So, if you modify the code and restart the server(process), the session data will be gone.

You can pick another storage from Compatible Session Stores to persist the session data in a database or a local file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading