Difference Between app.use() and router.use() in Express

后端 未结 3 1774
一整个雨季
一整个雨季 2020-12-12 11:12

I was just reading the documentation on express and found these two terms, app.use(); and router.use();

I know app.use(); is u

3条回答
  •  佛祖请我去吃肉
    2020-12-12 11:15

    router.use(); mounts middleware for the routes served by the specific router, app.use(); mounts middleware for all routes of the app (or those matching the routes specified if you use app.use('/ANYROUTESHERE', yourMiddleware());).

    Example use case could be an app with one router with standard routes and one router that handles api routes, which need a valid user.

    You would then mount the authentication middleware for the api router only with router.use(yourAuthMiddleware());.

    If you would have an app though that requires a valid user for all routes, mount the middleware for the app with app.use(yourAuthMiddleware());

提交回复
热议问题