我已经在nodejs中编写了用于注册的代码,以下是我的代码。我要检查数据库中是否已存在该电子邮件。如果是,则在客户端显示错误。我将React Native用作前端。以下是我的代码。
users.post('/registration', function(req,res){
var today = new Date();
var appData = {
"error" :"1",
"data" : "",
"userData" :"",
};
var userData = {
"pwd" : req.body.password,
"phone_no" : req.body.contact,
"user_name": "" ,
"status" : 1,
"date" : today,
}
database.connection.getConnection(function(err, connection){
if(err){
appData["error"] =1;
appData["data"] = "Internal Server Error";
res.status(500).json(appData);
} else{
connection.query("INSERT INTO user_registration SET ?" ,userData, function(err,result,fields){
var phone = userData.phone_no;
connection.query("SELECT user_id from user_registration WHERE phone_no=?", [phone], function(err,result,fields){
if(!err){
appData.error= 0;
appData["data"] = "User registered Successfully";
appData["userData"] = userData;
appData["user_id"] =result[0].user_id;
let token = jwt.sign(result[0], process.env.SECRET_KEY);
appData["token"] =token;
res.status(201).json(appData);
} else{
appData["data"] = "Error Occured";
res.status(400).json(appData);
}
console.log(appData);
});
});
connection.release();
}
});
});
答案 0 :(得分:1)
尝试这种方式..在插入数据之前,您必须检查电子邮件是否存在
connection.query("SELECT COUNT(*) AS cnt FROM tableName WHERE email = ? " ,
body.email , function(err , data){
if(err){
console.log(err);
}
else{
if(data[0].cnt > 0){
// Already exist
}else{
connection.query("INSERT INTO ..." , function(err , insert){
if(err){
// retunn error
}else{
// return success , user will insert
}
})
}
}
})