以下是我正在处理的代码,但我在执行时遇到错误。 请帮我创建同一页面上的登录和注册表单的路由。 当我使用此代码提交注册表单时,我收到一条错误消息,其中显示错误请求"
var express = require ('express');
var app = express();
var path= require('path');
var bodyParser = require('body-parser');
var mongoose = require("mongoose");
var nodemailer = require('nodemailer');
var transporter = nodemailer.createTransport();
var smtpTransport = require('nodemailer-smtp-transport');
var passport = require('passport');
var LocalStrategy = require('passport-local');
var passportLocalMongoose = require('passport-local-mongoose');
var User = require('./models/user');
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.static(path.join(__dirname, 'public')));
app.set("view engine", "ejs");
app.use(require('express-session')({
secret: 'Working on enroll Medicare',
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());
mongoose.connect("mongodb://localhost/registration");
app.post('/login-register.html', function(req,res)
{
var username = req.body.usernameregister;
var email = req.body.emailregister;
var password1 = req.body.password1register;
var password2 = req.body.password2register;
password1, password2: password2}
User.register(new User({username: username, email: email}), password1, function(err, user){
if(err){
console.log(err);
return res.render('error');
}
passport.authenticate('local')(req, res, function(){
res.redirect("/secret");
});
});
});
登录页面
app.post("/login-register.html", passport.authenticate('local', {
succesRedirect: "/secret",
failureRedirect: "/error"
}), function(req, res){ });
答案 0 :(得分:1)
我想你在这里可能有多个问题。以下是一些要检查的事项:
passport.use(new LocalStrategy(User.authenticate()));
。我不知道User.authenticate()
返回什么,但它应该返回一个带有参数function(username, password, done) {...}
的函数email
作为用户名。您需要将usernameField
添加到策略选项中:new LocalStrategy({usernameField: 'email'}, function(email, password, done){...})
passport.authenticate
函数中使用自定义回调非常有用,可以查看返回的错误是否提供了有关该问题的更多信息:passport.authenticate('local', function(err, user, info) {console.log(err, user, info)})