[英]Running the same code at the beginning of many Express.js routes
查看以下路線:
app.get('/', function (req, res) {
var legacy = false;
//LENGTHY CODE that sets legacy to true for old browsers
if (legacy === false) {
res.render('home');
} else {
res.render('legacy');
}
});
app.get('/other', function (req, res) {
var legacy = false;
//LENGTHY CODE that sets legacy to true for old browsers
if (legacy === false) {
res.render('other');
} else {
res.render('legacy');
}
});
//Many other routes like this with the legacy check.
問題是,如何避免在每條路線中重復冗長的代碼 ? 將其放入函數中並不是真正的解決方案,因為這引出了一個問題,如何避免在每個路由中都調用該函數?
有什么好的辦法嗎?
也許這就是所謂的中間件的目的?
想法將不勝感激。
是的,正如您所說的,這正是中間件的用途。
app.use(function (req, res, next) {
var legacy = false;
if (legacy) {
res.render('legacy');
} else {
next();
}
});
您可以使用next()
。 嘗試這個:
app.get(['/', '/other'], function(req, res, next){
//preprocessing here
next();
});
它接受路徑,路徑模式,正則表達式和數組。 如果您不希望某些路徑執行此預處理,則可以使用Regex否定這些路徑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.