我同时具有api auth的本地策略和jwt策略,并且不想使用cookie,这在刷新错误消息时似乎是一个问题。我得到UnhandledPromiseRejectionWarning: Error: req.flash() requires sessions
。有没有办法将这些消息作为api响应而不是401 unauthorized
?
这是本地身份验证中间件:
const requireLocalAuth = passport.authenticate("local", {
session: false,
failureFlash: true
});
这是我的本地策略并显示以下消息:
const passportLogin = new PassportLocalStrategy(
{
usernameField: "email",
passwordField: "password",
session: false,
passReqToCallback: true
},
async (req, email, password, done) => {
const schema = Joi.object().keys({
email: Joi.string()
.trim()
.email()
.required(),
password: Joi.string()
.trim()
.min(6)
.max(12)
.required()
});
try {
const form = await Joi.validate(req.body, schema);
} catch (err) {
return done(null, false, { message: err.details[0].message });
}
try {
const user = await User.findOne({ email: email.trim() });
if (!user) {
return done(null, false, { message: "Email does not exists." });
}
user.comparePassword(password, function(err, isMatch) {
if (err) {
return done(err);
}
if (!isMatch) {
return done(null, false, { message: "Incorrect password." });
}
return done(null, user);
});
} catch (err) {
return done(err);
}
}
);
编辑:我在调试器和反复试验的帮助下进行了此自定义回调,似乎可以正常运行。可以吗?
const requireLocalAuth = function(req, res, next) {
passport.authenticate("local", function(err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(422).send(info);
}
req.user = user;
next();
})(req, res, next);
};