ExpressJS 仅将中间件应用于路由器中的路由

Tom*_*mas 6 routing node.js express

我有应用程序,其中有公共路线和授权路线。公共路由也应该通过 auth,但如果 auth 失败,也没关系。

所以我有两个路由器:

var publicRoutes = express.Router();
var secretRoutes = express.Router();

publicRoutes
    .use(auth)
    .use(ignoreAuthError);

publicRoutes.get('/public', function(req, res){
    res.status(200).send({message: "public"});
}); 

secretRoutes
    .use(auth)
    .use(handleAuthError);

secretRoutes.get('/secret', function(req, res){
    res.status(200).send({message: "secret"});
}); 

...

app.use(publicRoutes);
app.use(secretRoutes);
Run Code Online (Sandbox Code Playgroud)

现在一切正常,但是如果我更改app.use公共路由的顺序会引发身份验证错误。此外,我无法收到任何 404、500 等错误,因为它们都经历了身份验证错误。

很明显,正在发生的事情是Router.use()应用于所有具有相同根的路由 - 在这种情况下"/"

因此,我认为如果我只auth在所有路由上使用中间件,然后将其他中间件直接添加到路由中,它应该可以正常工作。但这有点阻碍了我拥有多个路由器的意义。

我希望如果我使用Router.use()中间件,则仅当该特定路由器匹配它已设置的任何路由时才适用,而不是更改其他路由器的行为。

我理解正确吗?有没有办法解决这个问题,而实际上不必为每条路由添加中间件?

Ple*_*mor 3

有同样的问题,感谢@Explosion Pills 评论解决了。

坏的:

app.use(secretRoutes); // router.use calls won't be scoped to "/secret" 
app.use(publicRoutes); // public routes will be impacted
Run Code Online (Sandbox Code Playgroud)

好的:

app.use("/secret", secretRoutes); // router.use calls will be scoped to "/secret" 
app.use("/public", publicRoutes); // public routes won't be impacted
Run Code Online (Sandbox Code Playgroud)