Nodejs - 向用户注册/登录错误="无法读取属性' _id'未定义"

时间:2017-12-03 14:31:44

标签: node.js mongodb

我在NodeJ中创建身份验证。当我尝试登录用户/注册用户时,我收到错误。

无法读取属性' _id'未定义的

方法findById仅用于一个get路由。这是秘密获取路由,因此只有特定用户类型的用户才能访问此页面

我也使用了passportjs。它将数据发送到数据库。

这是我的注册和登录代码

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


mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost/ww", {useMongoClient: true});

app.use(bodyParser.urlencoded({extended:true}));
app.set("view engine", "ejs");

/*=========================
Setting up PassportJS
==========================*/

app.use(passport.initialize());
app.use(passport.session());

app.use(require("express-session")({
    secret: "King Nidge",
    resave: false,
    saveUninitialized: false
}));

passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser()); //Put it back in session
passport.deserializeUser(User.deserializeUser()); //Reading session, taking in data and decoding.

/*=========================
    Routes
==========================*/

app.get("/", function(req, res){
   res.render("landing"); 
});

app.get("/secret", function(req, res){
    User.findById(req.user._id, function(err, user){
        if(err){
            console.log(err);
        }
        else {
        if(user.role === "Landlord"){
              res.render("secret");
        }
        else {
            res.redirect("/");
        }}
    });

});



/*=========================
    Authentication Routes
==========================*/

//Register

app.get("/register", function(req, res){
   res.render("register"); 
});

app.post("/register", function(req, res){
    User.register(new User({username: req.body.username, email: req.body.email, role: req.body.role}), req.body.password, function(err, user){
        if(err){
            console.log(err);
            return res.render('register');
        } else {
            passport.authenticate("local")(req, res, function(){
                res.redirect("/secret");
            });
        }
    });

});

//Login

app.get("/login", function(req, res) {
    res.render("login");    
});

app.post("/login", passport.authenticate("local", {
    successRedirect: "/secret",
    failureRedirect: "/login"
}) ,function(req, res){
});

这是我的用户架构。

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    email: String,
    role: String
});

UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);

这是我的注册表格

<h1>Sign Up Form</h1>
<form action="/register" method="POST">
    <input type="text" name="username" placeholder="username">
    <input type="password" name="password" placeholder="password">
    <input type="email" name="email" placeholder="email">
    <input type="radio" name="role" value="Administrator">
    <input type="radio" name="role" value="User">
    <button>Submit</button>
</form>

克服此错误的任何提示?

1 个答案:

答案 0 :(得分:0)

请检查一下。

快速会话应在护照初始化和passport.session使用声明之前声明。

 app.use(require("express-session")({
  secret: "King Nidge",
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());