首页 > 解决方案 > 快速中间件中的重定向循环

问题描述

我有一个快速中间件,其路由定义的方式是,如果请求未通过身份验证,则会重定向到从静态文件提供的登录页面:

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

在登录功能中,我检查请求 url 并提供一个 html 文件。如果 urlstatic在路径的开头有 ,我想返回请求的文件。因此,当用户未经授权时,我将她发送到显示 index.html 的“/login”,其中在静态目录中有对 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在请求中检查的方式或路由中的优先级存在问题。

标签: node.jsexpressroutes

解决方案


问题似乎是next()登录中的功能。删除它允许应用程序按预期工作。


推荐阅读