“express-session” 在路由中的保存

huangapple go评论61阅读模式
英文:

express-session on saving on routes

问题

在server.js中,你声明了一个Express应用程序,并设置了会话(session)配置。在thread.js中,你有一个用于测试的方法,其中包含对会话的操作。

问题可能出在以下地方:

  1. 在thread.js中,你设置了req.session.test为'123123123123',但后来将其注释掉,这会导致会话中的test属性被删除,所以在后续的日志中出现undefined是正常的行为。

  2. 在将threadId添加到req.session.viewedThreads数组之前,你需要确保req.session.viewedThreads是一个数组。你可以在server.js中的会话配置中设置一个空数组,例如:

app.use(
    session({
        secret: 'bkepcraymanAbcd1234',
        resave: true,
        saveUninitialized: true,
        cookie: { secure: false },
        // Add an empty array to session
        store: new MongoStore({ mongooseConnection: mongoose.connection }),
        views: []
    })
);

然后,你可以在thread.js中进行以下操作:

// Check if req.session.viewedThreads is an array, if not initialize it as an empty array
if (!Array.isArray(req.session.viewedThreads)) {
    req.session.viewedThreads = [];
}

// Add threadId to viewedThreads
req.session.viewedThreads.push(threadId);

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

这样,你可以确保req.session.viewedThreads是一个数组,并且能够正确地将threadId添加到其中。

请确保在server.js中的会话配置中使用适合你的存储引擎(例如,MongoStore),并在thread.js中执行所需的操作来更新会话数据。希望这有助于解决问题。

英文:

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

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

答案1

得分: 1

> 警告 默认的服务器端会话存储 MemoryStore

会话数据存储在内存中。因此,如果您修改了代码并重新启动服务器(进程),会话数据将会丢失。

您可以从兼容的会话存储中选择另一个存储方式,将会话数据持久化到数据库或本地文件中。

英文:

> 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.

huangapple
  • 本文由 发表于 2023年7月6日 16:02:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76626709.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定