Reputation: 656
In Express, I'm using different routers for each of my routes, like this:
const express = require('express');
const postRouter = require('./postRouter');
const userRouter = require('./userRouter');
const app = express();
app.use('/posts', postRouter);
app.use('/users', userRouter);
And then in my router files, I have the routes.
However, let's say that on all my pages I'm using sessions. If I want to do this, I have to say router.use(sessionMiddleware);
in each router file.
My question is is that if I can still use multiple routers without having to specify the middleware in each file. I've tried app.use();
but that doesn't work.
Thank you
Upvotes: 1
Views: 262
Reputation: 114014
You need to do what you claim doesn't work:
app.use(sessionMiddleware);
However I can guess why your attempt doesn't work. It probably comes from your misunderstanding of how Express work.
At it's core express is a middleware processing engine. You configure a list of middlewares in Express (endpoints are also middlewares, they just happen to be the last to be executed) and Express will process them one at a time in order.
The last sentence is the most important to understand: Express will process middlewares one at a time in order.
So if you do something like
app.use('/posts', postRouter);
app.use('/users', userRouter);
app.use(sessionMiddleware);
What you are doing is tell express to:
postRouter
postRouter
is executed see if the route call the next()
function
without any argument. If next()
is called continue processing.next()
is called with any argument stop processing and proceed
to the error handler (by default this will send an error page back to
the browser)next()
is not called stop processinguserRouter
userRouter
is executed see if the route call the next()
function
without any argument. If next()
is called continue processing.next()
is called with any argument stop processing and proceed
to the error handlernext()
is not called stop processingsessionMiddleware
So if your flow (yes, it's a program flow, not simply API calls to Express) is like the above this means the sessionMiddleware
will not get executed for the /posts
and /users
routes.
This means you need to change your program flow as follows:
app.use(sessionMiddleware);
app.use('/posts', postRouter);
app.use('/users', userRouter);
As you can see, Express is very flexible. Say for example you want /posts
to use your session middleware but not /users
. You can do this instead:
app.use('/users', userRouter);
app.use(sessionMiddleware);
app.use('/posts', postRouter);
Upvotes: 1