Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript NodeJS护照重定向_Javascript_Node.js_Express - Fatal编程技术网

Javascript NodeJS护照重定向

Javascript NodeJS护照重定向,javascript,node.js,express,Javascript,Node.js,Express,我正在尝试在NodeJS和Express后端脚本上使用Passport实现用户重定向。我面临的问题是,我的登录页面不是默认主页,而是: localhost:3000/login 我已经设法做到了,如果用户未注册,他就无法访问其他页面,例如/index或/dashboard,但当我尝试访问硬编码URL时,某些内容会中断,例如: 如果我进入localhost:3000/即使我没有登录,也可以访问默认的index.html页面。只是想澄清一下-localhost:3000/index=localho

我正在尝试在NodeJS和Express后端脚本上使用Passport实现用户重定向。我面临的问题是,我的登录页面不是默认主页,而是:

localhost:3000/login
我已经设法做到了,如果用户未注册,他就无法访问其他页面,例如
/index
/dashboard
,但当我尝试访问硬编码URL时,某些内容会中断,例如:

如果我进入
localhost:3000/
即使我没有登录,也可以访问默认的
index.html
页面。只是想澄清一下-
localhost:3000/index
=
localhost:3000

如果我决定这样操作路由:
localhost:3000/Example/pages/index.html
localhost:3000/Example/pages/dashboard.html
,它将允许我访问页面,即使我已登录

我的问题是,如何限制用户操纵到默认主页和任何其他未在节点后端声明的页面的路由

我的节点路由代码:

app.get('/login',
        function(req, res){
            res.sendFile(path.join(__dirname + '/login.html'));
        });

    app.get('/index', isLoggedIn,
        function(req, res){
            res.sendFile(path.join(__dirname + '/index.html'));
        });


    app.post('/login',
        passport.authenticate('local', { failureRedirect: '/login' }),
        function(req, res) {
            res.redirect('/index');
        });

      app.post('/login',
    passport.authenticate('local', { failureRedirect: '/login' }),
    function(req, res) {
        res.redirect('/index');
    });
我试过用这个:

app.use(function(req, res, next) {
if (req.session.user == undefined) {  
      return res.render('/login', {  failureRedirect:'/login'  });
    }   
    else {
        next();
    }
});
但是我收到一个错误:没有指定默认引擎,也没有提供扩展。我不想使用JADE、handlebar或其他任何东西作为引擎,只想使用静态HTML


如何限制路由操作,而不必将其余的节点页面定义为
app.get(/something,function(req,res){})

您可以制作一个passport中间件来检查用户是否经过身份验证

isAuthenticated = (req, res, next) => {
  if (req.isAuthenticated()) {
    return next();
  }

  res.redirect('/login');
};
然后你就可以这样做了

app.get('/someroute', isAuthenticated, (req, res)=>{
    // do what you want
});

如果我只是用
'/'
而不是“
'/someroute”
或者让它空着呢?它对静态文件仍然有效吗?不管路由是什么,你可以使用任何你想要的。这里的想法是中间件已经过验证。Vanka不起作用。我仍然可以访问默认主页并操纵路由。所以我假设您在某处使用express.static?您可以尝试在上面添加一行,如:app.use(isAuthenticated)。我当前使用的是
app.all('*/*',isLoggedIn,function(req,res,next){res.sendFile(path.join(u dirname+'/login.html');})
但是当我访问路由:
localhost:3000
时,它不会重定向。这是我的主要问题。如果我使用带有斜杠的路由,它会重定向,但不会重定向默认的本地主机路径。