Express 响应未在 Sequelize 捕获处理程序中执行
Express response not executing in Sequelize catch handler
我正在使用护照和 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');
另请参阅:
我正在使用护照和 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');
另请参阅: