Javascript app.get()和app.route().get()之间的差异

Javascript app.get()和app.route().get()之间的差异,javascript,node.js,express,server,backend,Javascript,Node.js,Express,Server,Backend,这两种说法的区别是什么: app.get('/',someFunction); app.route('/').get(someFunction); 请注意,我没有比较router.get和app.get,假设您要在同一路径上执行三条路由: app.get('/calendarEvent', (req, res) => { ... }); app.post('/calendarEvent', (req, res) => { ... }); app.put('/calendarEve

这两种说法的区别是什么:

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.route('/calendarEvent',MIDDLEWARE_FUNCTION)。get((req,res)=>{…})
我们可以这样做吗?@ArjunSingh-我不这么认为,但是显示了
app.route('/events')。all(函数(req,res,next){/*为所有HTTP*/}运行)。get(…)
其中
.all()
就像中间件一样工作。好的,谢谢@jfriend00
app.get('/',someFunction); 
app.route('/').get(someFunction);