NodeJS + Express - Apply session middleware to some routes

前端 未结 2 707
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 10:21

I have an Express application with some routes, only two of them need to support sessions. I read everywhere that the middleware definition (app.use(express.session({...) ap

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-13 10:50

    Don't use app.use(express.session({ ... })).

    Instead, initialize the session middleware, save a reference to the resulting function then include it directly in the routes you want it on.

    var express = require('express'),
        app = express();
    
    var session = express.session({
        //session configuration
    });
    
    app.use(app.router);
    
    
    // must come after app.use(app.router);
    app.get('/your/route/here', session, function(req, res){
        // code for route handler goes here
    });
    

    Slightly simpler than the answer included in the update (you don't need the wrapper function).

提交回复
热议问题