NodeJS + Express - Apply session middleware to some routes

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

提交回复
热议问题