快速中间件中的重定向循环

我有一个表达方式明确的中间件,该中间件的定义方式是:如果请求未通过身份验证,则将其重定向到由静态文件提供的登录页面:

  app.use('/login',authMiddleware.login);
  app.get(['/static','/static*'],authMiddleware.login);
  app.use('/logout',authMiddleware.logout);
  app.use('/check-login',authMiddleware.checkLogin);
  // For any request that is not authenticated 'authenticat' 
  // would redirect  to /login
  app.use('*',authMiddleware.authenticate);

在登录功能中,我检查请求的网址并提供一个html文件。如果该URL的开头有static,我想返回所请求的文件。因此,当用户未经授权时,我将其发送到“ / login”,其中显示index.html,并且在静态目录中有对CSS和Js的引用:

module.exports.login = (req,resp,next) => {

  const name = req.originalUrl.split('/');
   // If the request is for /static/file.js or static/file.css then:
  if (name[1] === 'static') {
       // Send the file 
    console.dir(path.join(`${__dirname}${req.originalUrl}`));
    resp.sendFile(path.join(`${__dirname}${req.originalUrl}`));
  }
  if (name[1] === 'login') {     
    console.dir(path.join(`${__dirname}${req.originalUrl}`));
    resp.sendFile(path.join(`${__dirname}/static/index.html`));
  }
  next();
};

这是我的authenticate函数:

module.exports.authenticate = (req,res,next) => {
  if  (!req.session.accessToken) {
    res.redirect('/login');
  } else {
    return next();
  }
};

这适用于index.html文件,但不适用于静态目录提供的CSS / JS。对静态css / js的请求最终在重定向循环中结束。我怀疑登录功能逻辑以及检查请求中的/static或路由优先级的方式存在问题。

guxiaoke0510 回答:快速中间件中的重定向循环

问题似乎出在登录时的next()函数。删除它可以使应用程序按预期工作。

本文链接:https://www.f2er.com/3170116.html

大家都在问