检查是否使用了用户名-PassportJS [英] Check if username is taken - PassportJS
本文介绍了检查是否使用了用户名-PassportJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在用户创建帐户之前检查用户名是否未占用.我正在尝试使用AJAX和通行证构建一个一页应用程序.
I am needing to check that the username is not taken before a user creates an account. I am attempting to build a one page application with AJAX and passport.
当用户使用护照进行注册时,我该如何检查是否在发布之前取走了用户名?
How would I go about checking to see if the username is taken BEFORE posting when a user is registering using passport?
不确定从哪里开始.
谢谢!
app.post("/quiz", function(req, res){
var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
User.register(newUser, req.body.password, function(err, user){
// if(res.error){
if(err){
req.flash("error", err.message);
res.redirect('back')
return res.render("quiz");
} else {
passport.authenticate("local")(req, res, function(){
// req.flash("success", "Welcome to JobQuiz " + user.username);
res.redirect("jobquiz");
console.log(req.body.datapoint)
});
}
});
});
推荐答案
使用findOne函数首先查找用户是否存在.如果用户存在,那么您就可以返回错误
First find if the user exists using findOne function. If user exists then you can just return an error
app.post("/quiz", function(req, res){
User.findOne({username: req.body.username}, function(err, user){
if(err) {//error handling... }
if(user) { //user already exists. throw error accordingly}
//continue with your registration logic
var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
User.register(newUser, req.body.password, function(err, user){
// if(res.error){
if(err){
req.flash("error", err.message);
res.redirect('back')
return res.render("quiz");
} else {
passport.authenticate("local")(req, res, function(){
// req.flash("success", "Welcome to JobQuiz " + user.username);
res.redirect("jobquiz");
console.log(req.body.datapoint)
});
}
});
});
});
上面的代码在回调中处理.如果您想避免回调地狱,可以使用promises
The above code is handled in a callback. If you want to avoid callback hell you can use promises
这篇关于检查是否使用了用户名-PassportJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文