app.get()和app.route().get()的区别

5
这两个语句有什么区别:

app.get('/',someFunction);

app.route('/').get(someFunction);

请注意,我并不是在比较router.get和app.get。
1个回答

6
假设您希望在同一路径上执行三个路由:
app.get('/calendarEvent', (req, res) => { ... });
app.post('/calendarEvent', (req, res) => { ... });
app.put('/calendarEvent', (req, res) => { ... });

这样做需要您每次复制路由路径。

您可以尝试以下方式:

app.route('/calendarEvent')
  .get((req, res) => { ... })
  .post((req, res) => { ... })
  .put((req, res) => { ... });

这只是一种快捷方式,如果你有多个不同动词的路由都在同一路径上。我从未使用过这个功能,但显然有人认为它很方便。

如果你有某种通用的中间件仅适用于这三条路线,它可能会更加有用:

app.route('/calendarEvent')
  .all((req, res, next) => { ... next(); })
  .get((req, res) => { ... })
  .post((req, res) => { ... })
  .put((req, res) => { ... });

您也可以使用新的路由器对象来实现类似的功能。


如果我不解释一下,那么这两个语句之间没有任何区别(这是您所问的问题的一部分):

app.get('/',someFunction); 
app.route('/').get(someFunction);

它们做的事情完全相同。以下是关于第二个选项你可以做的其他事情。


app.route('/calendarEvent', MIDDLEWARE_FUNCTION).get((req, res) => { ... }) 我们可以这样做吗? - Arjun Singh
@ArjunSingh - 我不这么认为,但是文档显示app.route('/events').all(function (req, res, next) { /* runs for all HTTP verbs */ }).get(...),其中.all()运作像中间件。 - jfriend00

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接