这两个语句有什么区别:
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);
他们做的事情完全一样。我的其余回答是关于您可以使用第二个选项做些什么。
关于javascript - app.get() 和 app.route().get() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729136/