所以我在根路由'/'上提供一個網頁,這個頁面有一個身份驗證中間件。使用常規
app.use('/', authorizeFront, express.static('../client/dist'));
會導致每條路由都經過身份驗證,這是我試圖避免的。我也嘗試過使用正則運算式來完全匹配“/”,但它似乎不起作用。
app.use('/^/$/', authorizeFront, express.static('../client/dist'));
有沒有官方的方法可以做到這一點?謝謝!
uj5u.com熱心網友回復:
app.use 進行部分匹配。請改用 app.get。
uj5u.com熱心網友回復:
當使用app.use("/")它時,它將匹配任何以 開頭的路徑和方法"/",這是因為app.use()它是為全域中間件設計的。
相反,在這種情況下,您可以使用app.get("/", yourTargetedMiddlewaer)來定位特定路線和特定方法(GET)。
uj5u.com熱心網友回復:
另一種方法可能是:
app.use("*", (req, res, next) => {
if (req.baseUrl === "") { // For / requests baseUrl will be empty
// Call authenticator and then call next() if auth succeeds else call next(err)
} else {
console.info("Bypassing Authentication");
next();
}
});
這將針對所有請求命中中間件,但您可以控制要呼叫身份驗證器的請求。
uj5u.com熱心網友回復:
app.use(express.static(path.join(__dirname, 'public')));
app.use(function(req, res, next) {
if ( req.path === "/") {
console.log("request matches your special route pattern", req.url);
// return authorizeFront(); call your code
}
next();
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
我對此進行了測驗,并且我的控制臺僅在我使用這樣的 URL 時才會列印:
http://localhost:3000/ 或 http://localhost:3000
還要注意我使用的中間件的順序,基礎根中間件應該設定在頂部。您可以根據需要進行更多修改
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/429946.html
標籤:javascript 节点.js 表示
上一篇:初始化前無法訪問“用戶”
