我有这个中间件:
app.use((req, res, next) => {
console.log('test');
next();
});
我有这些动态路线:
app.get('/:path', (req, res, next) =>{
var pages = serverCache.pages;
for (let page of pages) {
if(req.params.path === page.path){
res.render('foo', {
helpers:helpers
});
return;
}//if
}//for
res.redirect('/');
});
当页面加载时,我希望 console.log('test')
只执行一次。但是它被执行了很多次。实际输出为:
test
test
test
test
...
它的发生是因为它在 for
循环中的每次迭代中执行。仅当该循环内的 if
语句条件为真时,我如何执行它?
最佳答案
我误解了函数何时执行。
之所以会执行多次,是因为它会为它检查的每条路由执行自己。 (对于之后的所有中间件功能)
为了让它只对我的动态路由执行,我将这两个函数都移到了底部。
app.get('static route')
app.post('static route')
app.use('static route')
app.use(); // moved it here
app.get('dynamic route')
关于javascript - 使用动态路由时,中间件功能被执行多次而不是一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41058588/