我使用 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
的问题是什么?以及如何修复它?
如果您需要其他任何东西,请告诉我
答案 0 :(得分:0)
使用 username
而不是 user
来查找用户
Company.findOne({ username: req.body.user });
您将 callback
样式与 async/await
混合使用,await
关键字对您没有影响,它不会等到查询完成。 await
关键字仅在您等待 Promise like object
(then
对象)时起作用。
我猜您正在使用 mongoose
,当前版本的 mongoose
支持 Promise 返回样式。
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'); ???
}
}
答案 1 :(得分:0)
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');
}
我在这方面做了更多的工作,可能控制器工作正常,问题可能出在中间件上。在上面讨论的注册案例中,中间件总是将“身份验证失败”记录到控制台。