javascript - 快速响应未在 Sequelize catch 处理程序中执行

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

我正在使用 Passport 和 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;

最佳答案

根据docs正确的语法是:

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

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

关于javascript - 快速响应未在 Sequelize catch 处理程序中执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40555358/

相关文章:

javascript - 否 'Access-Control-Allow-Origin' - CORS

node.js - 在 Express 的路由定义中指定子域

javascript - Bower_components 未使用 Express static 加载

google-chrome-extension - 是否可以使用 Chrome App Indentity Api 获取 Id token ?

php - 查找并删除 div 中的文本

javascript - 表单输入onload替代

javascript - 在部分 View 上加载脚本文件导致错误

javascript - 如何从数组中获取索引 - graphql?

google-chrome-extension - 在域范围内安装具有 Google API OAuth2 授权的 Chrome 扩展程序

oauth-2.0 - 为什么 Oauth2.0 说 "Client Password in request body not recommended"?