[英]Express.Router middleware is being called on all routes after routes are registered
我有一個簡單的應用程序,該應用程序具有一個登錄頁面和一個用於身份驗證用戶的部分,未身份驗證的用戶將從該部分重定向回登錄。 在所有路線的末尾,我都有app.all('*', ...)
,它返回404錯誤頁面。
通過身份驗證后,一切正常,但是如果我注銷並嘗試獲取不存在的路由,則會重定向到登錄頁面,而不是得到404響應。
我知道這是因為我添加了處理重定向的中間件,但我希望它僅在該路由器中指定的路由上起作用,而不是在中間件之后的所有路由(甚至是應用程序級路由)中都不能工作。
我目前看到的唯一解決方案是在每個受限制的路由中使用此authCheck中間件,而不是使用router.use
在全球范圍內注冊它,但是我仍然想知道是否有更好的方法?
const express = require('express')
module.exports = (app) => {
const authRouter = express.Router()
// ================================
// ========= Public Routes ========
// ================================
app.get('/login', () => { /* ... login route */ })
app.post('/login', () => { /* ... login route */ })
// ====================================
// ========= Restricted Routes ========
// ====================================
authRouter.use((req, res, next) => {
req.isAuthenticated()
? next()
: res.redirect('/login')
})
authRouter.get('/', () => { /* restricted route */ })
// register restricted routes
app.use(authRouter)
// ========================================
// ============ Other routes ==============
// ========================================
// error 404 route <--- this works only for authenticated users
app.get('*', (req, res) => {
res.status(404)
res.render('error404')
})
}
感謝您的任何想法..
嘗試此操作,您可以創建不帶auth的所有URL的數組,並檢查內部中間件。
const authMiddleware = (req, res, next) => {
/* Urls Without Auth */
const withoutAuth = ['/login'];
if (withoutAuth.includes(req.url) || req.isAuthenticated()) {
next();
} else {
res.redirect('/login');
}
};
app.use(authMiddleware);
const express = require('express')
// Note: FWIW I think it's better to organize your middleware
// into separate files and store them into separate directory
// So you could use it like that:
// const verifyAuthMiddleware = require('./middleware/verifyAuthMiddleware);
const verifyAuthMiddleware = (req, res, next) => {
req.isAuthenticated()
? next()
: res.redirect('/login')
};
module.exports = (app) => {
// ================================
// ========= Public Routes ========
// ================================
app.get('/login', () => { /* ... login route */ })
app.post('/login', () => { /* ... login route */ })
// ====================================
// ========= Restricted Routes ========
// ====================================
// You can add the middleware like that
app.get('/', [verifyAuthMiddleware], () => { /* restricted route */ });
// Or you can add a middleware to a group of routes like that
app.use('/user', [verifyAuthMiddleware]);
// And then every route that starts with "/user" uses the middleware
app.get('/user/settings', () => {});
app.get('/user/wallet', () => {});
app.get('/user', () => {});
app.post('/user/wallet', () => {});
// etc
// ========================================
// ============ Other routes ==============
// ========================================
// error 404 route <--- this works only for authenticated users
app.get('*', (req, res) => {
res.status(404)
res.render('error404')
})
}
謝謝您的回復。 最后,我這樣做是這樣的:
function authCheck (req, res, next) {
return req.isAuthenticated()
? next()
: res.redirect('/login')
}
// Product routes
const prodRouter = express.Router()
prodRouter.get('/', products.getlist)
prodRouter.get('/:uuid/:tab?', products.getbyId)
prodRouter.post('/:uuid/:tab?', products.update)
// Register product routes
app.use('/products', [authCheck, prodRouter])
// For all other routes return 404 error page
app.get('*', (req, res) => {
res.status(404).render('error404')
})
使用這種方法, authCheck
中間件僅在/product
路由上使用,因此當我訪問/missing-page
我正確地獲得了Error 404 page
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.