有一些更好的方法可以处理中间件的要求,通常用于您建议的方法:
仅在您需要的路由上包含您的身份验证中间件:
const authenticationMiddleware = (req, res, next) => {
// your login check logic
}
router.get('/api/users/me', authenticationMiddleware, (req, res, next) => {
// your route logic, this endpoint now requires you to be logged in, as you have specified your authentication middleware in the declaration,
})
router.get('/api/profiles/:profileId', (req, res, next) => {
// your route logic, this endpoint does not require you to be logged in as you have not put the middleware in the route delcaration
})
或者,根据调用路由的位置添加身份验证中间件:
router.get('/api/profiles/:profileId', (req, res, next) => {
// your route logic, this endpoint does not require you to be logged as we have not told our router to use the middleware yet
})
router.use(authenticationMiddleware)
router.get('/api/users/me', (req, res, next) => {
// your route logic, this endpoint now requires you to be logged in, as the router has been told to use the middleware at this point.
})
为什么要使用这些方法?尝试将您所做的所有router
或调用视为添加到堆栈中,该堆栈用于处理对您的站点或 API 的调用。app
当它通过查找路线工作时,它将调用它在途中找到的任何中间件。
这解决了必须声明需要或不需要特定身份验证的路由列表或数组等问题。
如果你想让它工作,你还需要确保调用next()
你的中间件,因为这告诉 express 继续遍历它拥有的所有路由/中间件。