Express中的app.use()和router.use()之间的区别 [英] Difference Between app.use() and router.use() in Express

查看:659
本文介绍了Express中的app.use()和router.use()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读快速的文档,并发现这两个术语, app.use(); router.use();

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

我知道 app.use(); 在节点中用于在路径上安装中间件,我们经常在大多数节点应用程序中使用它。但是什么是 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 ?

我阅读有关路由器的 here 。我也发现了类似的问题,关于SO 什么是express.Router之间的区别。并使用app.get?
app.all('*')和app.use('/')之间的区别,但是他们并没有真正回答我的问题。谢谢。

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.get 仅用于定义子路径。考虑这个例子:

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

现在,如果您在浏览器中打开 / first / sud 更小的函数将被调用。如果您打开第一个/用户,那么更大的将被调用。简而言之,app.use('/ first',路由器)将路径 / first 安装中间件,然后 c> router.get 相应地设置子路径

Now if you will open /first/sud in your browser, then smaller function will get called. If you will open first/user, then bigger will gets 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:

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

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

app.get('/user', smaller);

现在,如果您在浏览器中打开 / first ,那么 fun 将被调用,对于 / sud 更大将被调用,对于 / user ,函数 small 将被调用。 ...但是请记住这里 / first / sud ,没有函数将被调用。

Now if you will open /first in your browser then fun will get called and for /sud, bigger will get called and for /user, the function smaller will get called. ...but remember here for /first/sud, no function will get called.

此链接也可能有帮助: http://expressjs.com/api.html#router

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

这篇关于Express中的app.use()和router.use()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆