【问题标题】:Node express cookies get not set节点快递 cookie 未设置
【发布时间】:2018-11-17 01:48:01
【问题描述】:

我最近将我的项目从普通的 javascript 切换到了 typescript。除了会话处理之外,一切正常。

这是我目前的项目设置:

Server.ts
App.ts
/db/mongo/MongoHandler.ts

还有一些其他的东西,但这对这个问题应该不重要

MongoHandler.ts 有一个函数连接到 mongo db 并返回一个带有 mongoose.connection 对象的 promise。

与 mongodb 的连接工作正常。

App.ts 内部:

class App {

    public app: express.Application;
    private routes: Routes;

    constructor() {
        this.app = express();
        this.config();
    }

    private config(): void {

        //define less middleware
        this.app.use(less(path.join(__dirname, 'public')));

        //define static directory
        this.app.use(express.static(path.join(__dirname, 'public')));

        //define favicon
        this.app.use(favicon(path.join(__dirname, 'public', 'images', 'favicon.ico')));

        //add support for POST messages and cookies
        this.app.use(express.json());
        this.app.use(express.urlencoded({extended: false}));
        this.app.use(cookieParser());

        //define view engine
        this.app.set('views', path.join(__dirname, 'views'));
        this.app.set('view engine', 'pug');

        //mongo connection

        //session handling

        //loading config
        this.app.set('config', new ConfigHandler());

        //setup sessions
        var expiryDate = new Date(Date.now() + 60 * 60 * 1000);
        const MongoStore = connectMongo(session);

        const mongoHandler = new MongoHandler();
        mongoHandler.connect(this.app).then(connection => {
            this.app.use(session({
                secret: 'supersecret',
                store: new MongoStore({mongooseConnection: connection}),
                resave: false,
                saveUninitialized: true,
                cookie: {
                    secure: false,
                    expires: expiryDate
                }
            }));
        });
        this.app.set('mongo', mongoHandler);

        //define routes
        this.routes = new Routes(this.app);
        this.routes.routes();
    }
}

export default new App().app;

所以基本上每个 app.use 都在工作,除了会话的东西。 req.session 在每次请求时都未定义。

我知道我遗漏了一些东西,但我想不通。 它与旧的 javascript 版本的代码相同,可以正常工作。

【问题讨论】:

    标签: node.js typescript express


    【解决方案1】:

    app.use() 不能在这样的异步调用函数内部有效地调用。结果是您以这种方式添加的中间件将被添加到中间件链的末尾,这为时已晚(它应该在路由之前)。

    要使用常规的 Mongoose 连接,您可以致电 .connect(),但不必等待回调/承诺。根据the documentation

    // Basic usage
    mongoose.connect(connectionOptions);
    
    app.use(session({
      store: new MongoStore({ mongooseConnection: mongoose.connection })
    }));
    

    您需要重组您的MongoHandler 代码,以便执行类似的操作。或者,使用async/await 等待连接承诺得到解决,然后再继续该方法的其余部分,或者在回调中添加路由。

    【讨论】:

    • 谢谢。第一部分帮助很大。我通过将 mongooseConnection: <connection> 更改为 dbPromise: mongoHandler.connect 并在连接函数中返回一个承诺来解决它
    猜你喜欢
    • 2020-02-19
    • 2013-07-04
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 2020-04-02
    • 2011-08-13
    相关资源
    最近更新 更多