简体   繁体   English

会话不与 express-session 和 connect-mongo 保持一致

[英]Sessions not persisting with express-session and connect-mongo

My express server is using express-session and connect-mongo and it's generating a new session for each request from the same user instead of persisting one session like it's supposed to.我的 express 服务器正在使用 express-session 和 connect-mongo,它为来自同一用户的每个请求生成一个新会话,而不是像预期的那样保留一个会话。 This is my first time using express sessions but I don't think it's a problem with my code.这是我第一次使用快速会话,但我认为我的代码没有问题。 Whilst testing I'm the only user and when I look at my MongoDB there's a bunch of new sessions.在测试时我是唯一的用户,当我查看我的 MongoDB 时,有很多新会话。 Every time I make a request to a route that needs to use a session variable it generates another new session.每次我向需要使用会话变量的路由发出请求时,它都会生成另一个新会话。

Edit: The session id is not being stored by the client, thus causing a new session with every request.编辑:客户端没有存储会话 id,因此每个请求都会导致一个新的会话。 The correct set-cookie header is being sent so I'm not sure why it's not working.正在发送正确的 set-cookie 标头,所以我不确定为什么它不起作用。 I'm using Firefox as my client.我使用 Firefox 作为我的客户端。

Edit 2: Tried with Edge and Chrome and they aren't setting the session cookie either.编辑 2:尝试使用 Edge 和 Chrome,它们也没有设置会话 cookie。 I'm new to sessions so I have no clue why it isn't working properly.我是会话的新手,所以我不知道为什么它不能正常工作。

// 3rd party modules
const util = require('util');
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const morgan = require('morgan');
const mongoose = require('mongoose');
const config = require('config');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);

// Custom classes
const AuthService = require('./services/authService');

// Models
const Account = require('./models/account');

// Load .env config file
const envConfigResult = require('dotenv').config();
if (envConfigResult.error) {
    throw envConfigResult.error;
}

// Instances
let auth;
let upload = multer();
const app = express();

// Parse request data and store in req.body
app.use(bodyParser.json()); // json
app.use(bodyParser.urlencoded({ extended: true })); // x-www-form-url-encoded
app.use(upload.array()); // multipart/form-data

// Setup logging
app.use(morgan('dev'));

// JWT error handling
app.use(function (err, req, res, next) {
    // TODO: Implement proper error code
    res.status(401).send(err);
    if (err.name === 'UnauthorizedError') {
        res.status(401).send('invalid token...');
    }
});

async function main() {
    try {
        const mongoDbUrl = process.env.DB_HOST;
        // Use new url parser and unified topology to fix deprecation warning
        const mongoConnection = mongoose.connect(mongoDbUrl, { useNewUrlParser: true, useUnifiedTopology: true }).then(async function() {
            console.log(`Successfully connected to MongoDB database at ${mongoDbUrl}!`);
        }).catch(function(error) {
            console.log(`Error whilst connecting to MongoDB database at ${mongoDbUrl}! ${error}`);
        });
        mongoose.set('useCreateIndex', true); // Fixes deprecation warning
    } catch (err) {
        console.log(`Error whilst doing database setup! ${err}`);
    }
    try {
        app.use(session({
            store: new MongoStore({ mongooseConnection: mongoose.connection, ttl: 86400 }),
            secret: process.env.SESSION_SECRET,
            resave: false,
            saveUninitialized: false,
            cookie: {
                path: "/",
                maxAge: 3600000, // 1 hour
                httpOnly: false,
                secure: false // TODO: Update this on production
            }
        }));
        console.log("Sessions successfully initialized!");
    } catch (err) {
        console.log(`Error setting up a mongo session store! ${err}`);
    }
    try {
        // TODO: Initialize email service
        auth = new AuthService.AuthService();
        // TODO: Attach email service to auth service
    } catch (err) {
        console.log(`Error whilst doing initial setup. ${err}`);
    }
}

main();

// Routes
const rootRoute = require('./routes/root');
const tokensRoute = require('./routes/tokens');
const captchaRoute = require('./routes/captcha');

// Route middlewares
app.use('/v1/', rootRoute.router);
app.use('/v1/tokens', tokensRoute.router);
app.use('/v1/captcha', captchaRoute.router);

try {
    rootRoute.setAuthService(auth);
    tokensRoute.setAuthService(auth);
} catch (err) {
    console.log(`Error attaching auth service to routes! ${err}`);
}

var server = app.listen(8088, function() {
    let host = server.address().address;
    let port = server.address().port;

    if (host == "::") {
        console.log("Server running at http://127.0.0.1:%d", port);
    } else {
        console.log("Server running at http://%s:%d", host, port);
    }
});

As explained in the doc (or npm page) , it seems that you forgot one line :正如文档(或 npm 页面)中所述,您似乎忘记了一行:

app.use(session({
    secret: 'foo',
    store: new MongoStore(options)
}));

It turns out that modern browsers ignore set-cookie headers unless you include credentials: 'include' in your request.事实证明,现代浏览器会忽略 set-cookie 标头,除非您在请求中包含credentials: 'include' So I switched the client to using fetch instead of XMLHttpRequest and added credentials: 'include' to its options.因此,我将客户端切换为使用 fetch 而不是 XMLHttpRequest 并在其选项中添加了credentials: 'include' (Credentials are ignored if you don't have CORS set up correctly, so I had to do that as well.) Now it works fine. (如果您没有正确设置 CORS,凭据将被忽略,所以我也必须这样做。)现在它工作正常。

TLDR: Include credentials: 'include' in your request and make sure the server has CORS configured. TLDR:在您的请求中包含credentials: 'include'并确保服务器已配置 CORS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM