【问题标题】:Express response not executing in Sequelize catch handler快速响应未在 Sequelize catch 处理程序中执行
【发布时间】:2017-03-26 02:52:14
【问题描述】:

我正在使用护照和 OAuth 对我网站上的用户进行身份验证。我制作了中间件来检查用户是否使用 OAuth 登录以及他们是否在允许的用户列表中。中间件起作用并阻止用户在未经授权的情况下访问使用它的数据路由。问题在于,在 Sequelize catch 处理程序中无法在列表中找到用户后,永远不会调用响应,因此如果失败,它们永远不会被重定向,它只会显示没有数据的页面。

这是我的中间件。我知道正在到达catch,因为我可以看到console.log,但res.status('401').redirect(/admin/login); 永远不会发生。让我知道代码的其他部分是否有用。提前感谢您的所有帮助!

'use strict';
const clc = require(`cli-color`);
const models = require('../models');
const User = models.User;

function isLoggedIn(req, res, next) {
  console.log(clc.red.bgBlue(` ::: `), req.user);
  res.header('Access-Control-Allow-Credentials', true);
  models.sql.sync()
    .then(() => {
      User.findOne({
        where: {
          email: req.user.unique_name
        }
      });
    })
    .then((user) => {
      if (req.isAuthenticated() && user !== null && user.email === req.user.unique_name) { // if user is authenticated in the session and the user email matches the user found in the db, carry on
        return next();
      } else {
        // if they aren't send not authorized
        res.status('401').redirect(`/admin/login`);

      }
    })
    .catch((err) => {
      console.log(clc.red.bgWhite(`ERR  ::::  )`), err);
      res.status(`401`).redirect(`/admin/login`);
    });

}

module.exports = isLoggedIn;

【问题讨论】:

    标签: javascript express oauth-2.0 passport.js sequelize.js


    【解决方案1】:

    根据docs正确的语法是:

    res.redirect(401, 'http://example.com');
    

    另请参阅: Chaining Express.js 4's res.status(401) to a redirect

    【讨论】:

    • 谢谢假鱼,我整个早上都在用这个头撞墙!
    猜你喜欢
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 2022-01-01
    相关资源
    最近更新 更多