2 回答
TA贡献1794条经验 获得超8个赞
您正在同时执行 2 个异步操作。他们最终都试图res.redirect('...');在用户已经被重定向后无法重定向。您if (userExists == false) {在上面的块中进行检查之前执行。
你可以像这样链接你的回调:
router.post('/', function(req, res, next) {
ssn = req.session;
ssn.firstName = req.body.fname;
ssn.lastName = req.body.lname;
ssn.userEmail = req.body.email;
ssn.userPass = req.body.pass;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("projectOne");
let myInfoLog = {
email: ssn.userEmail // Don't include the password!
};
// Check if email exists
dbo.collection("userInfo").findOne(myInfoLog, function(err, data) {
if (data.email) {
ssn.signUpError = "User email already exists";
console.log("data returns an active email");
db.close();
res.redirect('/');
} else {
const myInfo = {
fname: ssn.firstName,
lname: ssn.lastName,
email: ssn.userEmail,
pass: ssn.userPass
};
// Insert user
dbo.collection("userInfo").insertOne(myInfo, function(err, data) {
if (err) throw err;
console.log("collection inserted");
ssn.firstName = data.ops[0].fname;
ssn.lastName = data.ops[0].lname;
ssn.userEmail = data.ops[0].email;
ssn.userPass = data.ops[0].pass;
console.log("welcome! " + ssn.firstName + " " + ssn.lastName);
db.close();
res.redirect('/profile');
});
}
});
});
});
module.exports = router;
TA贡献1864条经验 获得超2个赞
您应该将您的if (userExists == false) {块移动到第一个查找中。
dbo
.collection("userInfo")
.findOne(myInfoLog, function(err, data) {
if (data.email) {
// handle case where user already exists
} else {
// handle case where user doesn't exist yet
}
添加回答
举报
