我有一个简单的应用程序,它有一个登录页面和一个经过身份验证的用户部分,未经身份验证的用户将从该部分重定向回登录。在我所有路由的末尾,我有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')
})
}
感谢您的任何想法..
试试这个,你可以在没有身份验证的情况下创建一个包含所有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
。