Node js保持重定向-中间件 [英] Node js Keeps redirecting - Middleware

查看:67
本文介绍了Node js保持重定向-中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node js和express编写中间件.如果用户未通过身份验证,则会将其重定向到登录页面.

I am trying to write a middleware using node js and express. If user is not authenticated it will redirect him to login page.

这是可行的,但是一旦重定向到登录页面,它就会一次又一次地重定向到登录页面.

That's working, but once redirected to login page, it keeps redirecting to login page again and again.

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'));
   }

});

控制台(循环):未在个人资料上通过身份验证的用户

Console(loop): not authenticated user at profile

Firebase身份验证方法

Firebase method for authentication

function isAuthenticated(){
   var user = firebase.auth().currentUser;
   console.log(user);
   if(user && user !== null){
       return true;
   }else{
       return false;
   }
}

它返回空值

推荐答案

我不会使用重定向,而是编写一个 authenticationRequired 中间件.该中间件将发送 401 状态码并显示登录页面,或将请求转发给下一个回调.

I wouldn't use a redirect, but write an authenticationRequired middleware. This middleware would either send a 401 status code and display the login page, or pass the the request forward to the next callback.

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'));
});

通过这种方式,您无需手动跟踪用户在第一种情况下尝试打开的网址,并且在登录后,用户将停留在正确的网址上.

This way you would not need to manually keep track of the url the user tried to open in the first case and after login the user will stay on the correct url.

此外,您将使用正确的状态代码,而不是 302 告诉浏览器该资源在其他地方是临时的,您发送的 401 会告诉浏览器浏览器需要验证才能显示所请求的资源.

Beside that you would use the correct status codes, instead of the 302 which tells the browser that the resource is temporary at another places you send the 401 which tells the browser that an authentication is required to display the requested resource.

这篇关于Node js保持重定向-中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆