var express = require('express');
var router = express.Router();
router.use(function(req, res, next){
console.log(req.user)
if(!req.user){
res.redirect('/login');
}else{
res.locals.username = req.user.username;
return next();
}
});
//this won't work
router.get('/register', function(req, res, next) {
res.render('register');
});
第一个块有意义且有效,我能够拥有一个带有受保护路由的登录系统。但在同一时间它破坏了我的第二位,它会显示登录页面,尽管我试图nagivate到localhost:3000 / register。
答案 0 :(得分:1)
当您使用router.use()
时,您告诉路由器在所有下一个roter.get()
路由中使用该功能中间件。所以在这里,顺序是有道理的。如果你关心订单,你可以做@bloodyKnuckles做的事情。或者,如果您想保留路线的模式,可以执行以下操作:
// Routes that don't need authorization like register
router.get('home',...);
router.get('register',...);
// Use your authorization middleware
router.use(function(req, res, next){
console.log(req.user)
if(!req.user){
res.redirect('/login');
}else {
res.locals.username = req.user.username;
return next();
}
});
// At this point you're using the authorization middleware.
// Any routes declared from here will call authorization middleware before its handler.
router.get('profile', ...);
答案 1 :(得分:0)
使用快速路由中间件选项将受保护路由与不受保护的路由区分开来。
// unprotected routes (no auth middleware)
router.get('/login', function(req, res, next) {
res.render('login');
});
router.get('/register', function(req, res, next) {
res.render('register');
});
// protected route (see auth middleware here)
router.get('/userinfo', authorize, function(req, res, next) {
res.render('userinfo');
});
function authorize (req, res, next){
console.log(req.user)
if(!req.user){
res.redirect('/login');
}else{
res.locals.username = req.user.username;
return next();
}
}
仅在受保护的路线中包含您的授权中间件:
router.get(path, [middleware (optional),] callback)