控制器没有按预期工作



我使用MVC来制作一个NodeJS服务器,这是其中一个控制器:

module.exports.create_user = async function (req, res) {
// console.log(req.body);
// console.log(req.user);
await Company.findOne({ user: req.body.user }, function (err, user) {
if (user) {
return res.redirect('/login');
}
else {
if (req.body.password == req.body.confirm_password) {
Company.create({
"country": req.body.country,
"username": req.body.user,
"password": req.body.password
});
}
else {
console.log('Passwords didnt match');
}
}
});
req.session.save(() => {
return res.redirect('/profile');
})
}

这段代码应该做什么?

查找用户是否已经存在;如果是,它将重定向到/login。如果不存在这样的用户,它应该创建一个新用户并重定向到/profile

这段代码是做什么的?

无论用户是否存在,代码总是重定向到/login。此外,在数据库中创建了一个用户,因此每次有新用户想要注册时,该用户都需要注册,然后登录才能访问/profile

这里不允许重定向到/profile的问题是什么?如何解决这个问题?如果您还需要什么,请告诉我。

使用username代替user查找用户

Company.findOne({ username: req.body.user });

你是混合callback风格与async/await,await关键字不影响你,它不会等到查询完成。当您等待Promise like object(then可对象)时,await关键字正在工作。

我猜你使用的是mongoose,mongoose的当前版本支持承诺返回样式。

module.exports.create_user = async function (req, res) {
// console.log(req.body);
// console.log(req.user);
try {
// Use `username` instead of `user` to find a user
const user = await Company.findOne({ username: req.body.user }); // callback is not passed, it will return a Promise
if (user) {
return res.redirect('/login');
}
if (req.body.password == req.body.confirm_password) {
await Company.create({ // wait until user is created
"country": req.body.country,
"username": req.body.user,
"password": req.body.password
});
// then redirect page
req.session.save(() => {
return res.redirect('/profile');
});
} else {
console.log('Passwords didnt match');
// what happen when password didn't match
// return res.redirect('/login'); ???
}
} catch (error) {
// something went wrong
// return res.redirect('/login'); ???
}
}
passport.checkAuthentication = async function (req, res, next) {
console.log(req.user);
let auth_status = await req.isAuthenticated() ? "sucess" : "failure";
console.log(`Authentication ${auth_status}`);
// if the user is signed in, then pass on the request to the next function(controller's action)
if (await req.isAuthenticated()) {
return next();
}
// if the user is not signed in
return res.redirect('/login');
}

我在这方面做了更多的工作,可能控制器工作正常,问题可能在中间件中。在上面讨论的注册案例中,中间件总是将"身份验证失败"记录到控制台。

最新更新