NodeJS + Express - Apply session middleware to some routes

前端 未结 2 708
没有蜡笔的小新
没有蜡笔的小新 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:43

    The problem is actually your route for /path1, which is defined before express.session is being used.

    When you declare a route handler in Express, at that moment the router middleware (which handles all routes) will get inserted into the middleware chain. That means that if you haven't yet app.use'd any middleware which will be used by future routes (like your handler for /path2), they will never get called when handling any route.

    If you move your handler for /path1 to after app.use(express.session(...)), it will work without having to resort to tricks.

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题