我有一个简单的应用程序,它有一个登录页面和一个用于经过身份验证的用户的部分,未经身份验证的用户从中被重定向回登录。在我所有的路线结束时,我有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')
})
}
感谢您的任何想法..