简体   繁体   中英

Multiple express's routers using the root path

I run into a trouble using the express's router.

Here is a sample of code :

// file.js (1st to be imported)
module.exports = function (app) {
    app.use('/', fileRouter);
};

fileRouter.get('/file', /* do stuff */ );

// user.js
module.exports = function (app) {
    app.use('/', userRouter);
};

userRouter.get('/user', /* do stuff */ );
userRouter.get('/userList', /* do stuff */ );

We cannot prefix our routers and we want not to change our path architecture.

It seems that the two regex routers are added but duplicated.

It might look like :

/
=> /file

/
=> /user
=> /userList

Instead of

/
=> /file
=> /user
=> /userList

So instead of looking for the two routers, it stops at the first one.

Do you know how we can address this problem ?

If a route matches and you still want the subsequent routes to run if they match, then use the third function parameter of the route's callback:

userRouter.get( '/', function( req, res, next ) {  
  /* Do something... */
  next();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM