我正在尝试使用 Node js 和 Express 编写一个中间件。如果用户未通过身份验证,则会将其重定向到登录页面。
这是可行的,但是一旦重定向到登录页面,它就会一次又一次地重定向到登录页面。
app.get('/profile',function(req,res){
if (isAuthenticated()) {
res.sendFile(path.join(__dirname+'/site/profile.html'));
}else{
console.log('not authenticated user at profile');
res.redirect('/login');
}
});
登录
app.get('/login',function(req,res){
if (isAuthenticated()) {
res.redirect('/profile');
}else{
res.sendFile(path.join(__dirname+'/login.html'));
}
});
编辑:
控制台(循环):配置文件中的用户未经过身份验证
Firebase 身份验证方法
function isAuthenticated(){
var user = firebase.auth().currentUser;
console.log(user);
if(user && user !== null){
return true;
}else{
return false;
}
}
返回 null
最佳答案
我不会使用重定向,而是编写一个 authenticationRequired
中间件。该中间件要么发送 401
状态代码并显示登录页面,要么将请求转发到下一个回调。
function authenticationRequired(req, res, next) {
if( isAuthenticated() ) {
next()
} else {
res.status(401).sendFile(path.join(__dirname, 'login.html'));
}
}
// register the middleware for only one route
app.get('/profile', authenticationRequired, function(req,res) {
res.sendFile(path.join(__dirname, 'site/profile.html'));
});
// or register the middleware for all routes that follow
app.use(authenticationRequired)
app.get('/profile', function(req,res) {
res.sendFile(path.join(__dirname+'/site/profile.html'));
});
这样您就不需要手动跟踪用户在第一种情况下尝试打开的网址,并且登录后用户将保留在正确的网址上。
除此之外,您还可以使用正确的状态代码,而不是使用 302
来告诉浏览器该资源在其他位置是临时的,您发送的 401
告诉浏览器浏览器需要进行身份验证才能显示请求的资源。
关于javascript - Node js 不断重定向 - 中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45144678/