我正在 Nodejs 中实现一个简单的用户注册表单。我正在使用 Express 框架、Mongodb 和 Monk。我已经成功实现了正常的数据库插入。但是现在,当我添加代码以首先检查输入的电子邮件或用户名是否存在时,它已经失控了。问题是,当找到具有相同电子邮件或用户名的条目时,我会使用它res.end
来发送错误响应,但代码不会停在那里并继续执行其他条件并最终插入文档而不管条件如何,有时会出错那个can't set headers after they are sent
。下面是我的 ajaxsignup 路由代码
router.post('/ajaxsignup', function(req, res){
var db = req.db;
var formdata = req.body;
var collection = db.get('userscollection');
res.setHeader('Content-Type', 'application/json');
var emailExists = collection.findOne({"email": formdata.email}, function(err, doc){
if(err)
{
response = {'status': 0, 'err_code': err.code, 'err_msg': err.err};
res.end(JSON.stringify(response));
}
else
{
if(doc)
{
response = {'status': 0, 'err_code': 0, 'err_msg': 'This email id is already registered. Please use a different one.'};
res.end(JSON.stringify(response));
}
}
});//emailExists
var usernameExists = collection.findOne({"username": formdata.username}, function(err, doc){
if(err)
{
response = {'status': 0, 'err_code': err.code, 'err_msg': err.err};
res.end(JSON.stringify(response));
}
else
{
if(doc)
{
response = {'status': 0, 'err_code': 0, 'err_msg': 'This username is already in use. Please use a different one.'};
res.end(JSON.stringify(response));
}
}
});//usernameExists
formdata.created = new Date();
formdata.last_updated = formdata.created;
collection.insert( formdata, function(err, doc){
if(err)
{
response = {'status': 0, 'err_code': err.code, 'err_msg': err.err};
}
else
{
response = {'status': 1, 'msg': 'Thank you. You can proceed to login now.'};
}
res.end(JSON.stringify(response));
});//insert
});//ajaxsignup