我正在尝试检查数据库中是否已存在该用户。我正在使用javascript函数从客户端将用户的电子邮件ID发送到节点js路由。路由应查找数据库中是否存在用户。但所有结果都是无效的。
/* this is the route*/
router.route('/checkUserInDatabase:email')
.get(async(req,res)=>{
const user = await User.findOne({ 'email': req.params.email });
console.log(user);
});
/* this is the client side function*/
function checkifEmailExists(x){
$.get('/users/checkUserInDatabase:'+ x , function(data, status){
if(data=='true'){
alert('email exists');
}
if(data=='false'){
alert('email does not exist');
}
});
}
问题出在你不应该在客户端使用:
的路由中,应该是
'/users/checkUserInDatabase/'+ x
和服务器端应该是
'/checkUserInDatabase/:email'
看起来您需要在控制台.log之后立即res.send(JSON.stringify(user));
。