【发布时间】:2019-11-05 19:43:21
【问题描述】:
这两种说法有什么区别:
app.get('/',someFunction);
app.route('/').get(someFunction);
请注意,我不是在比较 router.get 和 app.get
【问题讨论】:
标签: javascript node.js express server backend
这两种说法有什么区别:
app.get('/',someFunction);
app.route('/').get(someFunction);
请注意,我不是在比较 router.get 和 app.get
【问题讨论】:
标签: javascript node.js express server backend
假设你想在同一条路径上做三条路线:
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) => { ... }) 我们可以这样做吗?
app.route('/events').all(function (req, res, next) { /* runs for all HTTP verbs */ }).get(...) 其中.all() 像中间件一样工作。