nodejs中的错误请求

时间:2016-11-09 17:12:48

标签: node.js express mongoose passport.js mongoose-plugins

我使用passportjs和passport-local-mongoose来创建用户注册。这是我的代码

var express         =require("express"),
    app             =express(),
    bodyParser      =require("body-parser"),
    passport        =require("passport"),
    LocalStrategy   =require("passport-local"),
    User            =require("./models/user"),
    mongoose        =require("mongoose"),
    exphbs      =require("express-handlebars");

mongoose.connect("mongodb://localhost/lone");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
var hbs = exphbs.create({
    defaultLayout: 'main',


    partialsDir: [

        'views/partials/'
    ]
});
app.use(express.static(__dirname +"/public"))

app.engine('handlebars', hbs.engine);
app.set("view engine", "handlebars");

app.use(require("express-session")({
    secret:"You are beautiful",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req,res,next) {
    res.locals.currentUser=req.user;
    next();

});
//Auth Routes
app.get("/signup",function(req,res){
    res.render("signup");
});
app.get("/",function(req,res){
res.render("home");
});
app.post("/signup",function(req,res,next){
    var newUser= new User({username: req.body.userName,name:req.body.firstName,email:req.body.email});
    User.register(newUser, req.body.password, function(err,user){
        if (err){
            console.log(err);
            res.redirect("/login")
            return next();
        }
        passport.authenticate("local")(req,res,function(){

            res.redirect("/");
            return next();
        });
    })
});
app.get("/login",function(req,res){
    res.render("login");
});
app.get("/logout",function(req,res){
    req.logout();
    res.redirect("/");
});
app.get("/",function (req,res) {
    res.render("home");

});
app.listen(3000,function(){
    console.log("started");

});

当我点击提交注册按钮时,我收到一条错误消息,指出错误请求。这是我在控制台中收到的消息 {[UserExistsError:具有给定用户名的用户已经注册]   name:'UserExistsError',   消息:'具有指定用户名的用户已注册'}

2 个答案:

答案 0 :(得分:0)

您的代码没有任何问题。

您正在尝试使用已经使用的用户名注册用户。您可以像这样更优雅地处理:

app.post("/signup",function(req,res,next){
  var newUser= new User({username: req.body.userName,name:req.body.firstName,email:req.body.email});
  User.register(newUser, req.body.password, function(err,user){
    if (err){
        console.log(err);
        return next(err);
    }
    passport.authenticate("local", function(_err, user){
        if(_err) return next(_err);
        res.redirect("/");
        return next();
    });
  })
});

答案 1 :(得分:0)

我遇到了相同的错误,该错误不是已经注册的用户名。这是因为您的电子邮件已在数据库中注册。