Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

node.js - Difference Between app.use() and router.use() in Express

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...