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



这两个语句之间有什么区别:

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

请注意,我没有比较router.get和app.get

假设您想在同一路径上进行三个路线:

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

他们做同样的事情。我的其余答案是关于第二个选项可以做什么。

最新更新