我正在读express上的文档,发现了这两个术语,app.use();router.use();

我知道在一条路径上, node 中使用app.use();表示Mounting a middleware,我们通常在大多数 node 应用程序中使用app.use();.但router.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仅用于定义子路径.考虑这个例子:

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,则会调用smaller函数.
  • 如果打开/first/user,则会调用bigger函数.

简而言之,app.use('/first', router)在路径/first处装载中间件,然后router.get相应地设置子路径.


但如果我们使用以下方法:

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

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

app.get('/user', smaller);
  • 如果你在浏览器中打开/firstfun会被调用,
  • 对于/sudbigger将被调用
  • 对于/usersmaller将被调用

但是记住,对于/first/sud,没有函数会被调用.

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

Node.js相关问答推荐

如何使用多个OR参数从多个集合聚合

从目录中获取所有文件,而不是NodeJS中的单个文件

为什么在导出的函数中调用node-sqlite3中的数据库方法时不起作用?

在对象的嵌套数组中使用$lookup,创建多个记录作为响应,mongodb

使用 axios 和 Cheerio (Node js) 抓取 google 搜索

DynamoDB 分页数据检索

如何使用Next.js/Node/TS正确地上传至S3

Mongoose post中间件触发deleteMany

我如何保护nodejs中的路由

登录用户并获取他们的个人资料

在快速路由中使用 axios 会在数据字段中返回特殊字符而不是 json

NPM 错误:修复upstream 依赖冲突安装 NPM 包(云功能)

Node.js |如何在微服务之间转发标头?

将 myproject/.npmrc 与注册表一起使用

如何在不全局安装的情况下在 Node REPL 中要求 node 模块?

如何brew安装特定版本的Node?

npm WARN 不推荐使用 graceful-fs@3.0.8:graceful-fs 版本 3

安装 node 包时可以使用自定义目录名称而不是node_modules吗?

如何从 Node.js 应用程序Ping?

FireStore 如果不存在则创建一个文档