I was just reading the documentation on express and found these two terms, app.use();
and router.use();
I know app.use();
is used in node for Mounting a middleware at a path, and we often use it in most of the node apps. but what is router.use();
are they both same? if not, whats the difference ?
I read about router here. I also found similar questions on SO What is the difference between "express.Router" and routing using "app.get"? and Difference between app.all('*') and app.use('/'), but they do not really answer my question. Thanks.
Router class can be used 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"." Possible duplicate of What is the difference between "express. Router" and routing using "app.
The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express. js.
The app. use() method mounts or puts the specified middleware functions at the specified path. This middleware function will be executed only when the base of the requested path matches the defined path.
app. use only see whether url starts with specified path;app. all will match complete path.
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);
smaller
function will get called. 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);
fun
will get called, bigger
will get called smaller
will get calledBut remember for /first/sud, no function will get called.
This link may also help: http://expressjs.com/api.html#router
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With