Express 中 app.use()和 router.use()的区别

我正在阅读关于 Express 的文档,发现了这两个术语 app.use();router.use();

我知道 app.use();在节点中用于 安装中间件的某个路径,并且我们经常在大多数节点应用程序中使用它。但是什么是 router.use();它们都是一样的吗?如果没有,又有什么区别呢?

我看过 给你路由器。我也发现类似的问题在 SO < a href = “ https://stackoverflow. com/questions/23607058/What-is-the-different-between-Express-router-and-routing-using-app-get”> 什么是“ Express”之间的区别。路由器和使用“ app.get”的路由? 和 App.all (& # 39; * & # 39;)和 app.use (& # 39;/& # 39;)之间的区别,但他们没有真正回答我的问题。谢谢。

89021 次浏览

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());

router.get is only for defining subpaths. Consider this example:

var router = express.Router();


app.use('/first', router); // Mount the router as middleware at path /first


router.get('/sud', smaller);


router.get('/user', bigger);
  • If you open /first/sud, then the smaller function will get called.
  • If you open /first/user, then the bigger function will get called.

In short, app.use('/first', router) mounts the middleware at path /first, then router.get sets the subpath accordingly.


But if we instead use the following:

app.use('/first', fun);


app.get('/sud', bigger);


app.get('/user', smaller);
  • If you open /first in your browser, fun will get called,
  • For /sud, bigger will get called
  • For /user, smaller will get called

But remember for /first/sud, no function will get called.

This link may also help: http://expressjs.com/api.html#router

app.use() used to Mounts the middleware function or functions at the specified path,the middleware function is executed when the base of the requested path matches path.

router.use() is used to middleware function or functions, The defaults mount path to “/”.

But in app.use() you will have to give a specified path like that:

 var adsRouter = require('./adsRouter.js');
app.use('/ads', adsRouter);

or

app.use('/ads', function(req, res, next) {


// write your callback code here.


});

But while using router.use() you can give only middleware, like this:

router.use(function(req, res, next) {
console.log('%s %s %s', req.method, req.url, req.path);
next();
});

or

router.use('/test', function(req, res, next) {
// write your callback code here.
next();
});

or

//in router.js


router.use('/admin', authUtil.verifySessionId, authUtil.verifyLisencee);
router.post('/admin', controllerIndex.ads.adListingAdmin);

In the above code when the end point is '/admin' then first it will call the authUtil.verifySessionId and authUtil.verifyLisencee then it will execute next line with 'admin' end point and according to controllerIndex.ads.adListingAdmin method.

app.use(middleware): application-level middleware.

router.use(middleware): router-level middleware.

("middleware" refers to methods/functions/operations that are called between processing the request and sending the response.)

See https://expressjs.com/en/guide/using-middleware.html for a comparison of different types of middleware used in an Express app.

When looking at the express js docs for Routing (https://expressjs.com/en/guide/routing.html#express-router):

Use the express.Router class to create modular, mountable route handlers. A Router instance is a complete middleware and routing system; for this reason, it is often referred to as a “mini-app”.

A Router created with express.Router() is no different than an app created with express() in terms of functionality; it's like a logical grouping of routes/handlers/services/databases/etc. The biggest difference is the scope that it affects. A router just affects its own scope while the app is like the master/global scope for your web/app server. You could have many routers or "apps" running on one main app/web server instance. This is why you could listen to requests on an app instance via app.listen(80) but not on a router.