app.js
require('dotenv').config()
const express = require('express')
const bp = require('body-parser')
const app = express()
const session = require('express-session')
const passport = require('passport')
const passportLocalMongoose = require('passport-local-mongoose')
const mongoose = require('mongoose')
app.use(express.static('public'))
app.use(bp.urlencoded({extended:true}))
app.set('view engine','ejs')
app.use(session({
secret:process.env.SECRET,
resave:false,
saveUninitialized:true
}))
app.use(passport.initialize())
app.use(passport.session())
mongoose.connect('mongodb://localhost:27017/todoDB',{useNewUrlParser:true,useUnifiedTopology:true})
const userSchema = new mongoose.Schema({
name:String,
email:String,
password:String,
googleId:String,
})
userSchema.plugin(passportLocalMongoose)
const users = mongoose.model('user',userSchema)
passport.use(users.createStrategy())
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
users.findById(id, function(err, user) {
done(err, user);
});
});
app.get('/',function(req,res){
res.render('home')
})
app.post("/", function(req,res){
users.register({username:req.body.username,name:req.body.name},req.body.password,function(err,user){
if(err){
res.redirect("/")
}
else{
passport.authenticate("local")(request,response,function(){
response.redirect("/home")
})
}
})
})
app.get("/home",function(req,res){
if(req.isAuthenticated()){
users.find({},function(err,data){
res.send(data)
})
}
else{
res.redirect("/login")
}
})
我在表单(名称,电子邮件,密码)上为我的用户提供3个字段。表单中的用户信息将插入数据库中,但无法使用authenticate方法对用户进行身份验证。如果用户已经通过身份验证,我想将用户重定向到主页。验证在这里不起作用。我的代码有什么问题?