gpt4 book ai didi

javascript - Nodejs 中的 Passport 身份验证

转载 作者:行者123 更新时间:2023-12-03 05:15:24 25 4
gpt4 key购买 nike

下面是我正在处理的代码,但我在执行时遇到错误。请帮助我为同一页面上的登录和注册表单创建路由。当我使用此代码提交注册表时,收到一条错误消息,提示“错误请求”

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){ });

最佳答案

我认为您可能遇到多个问题。以下是一些需要检查的事项:

  • 您有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)})

关于javascript - Nodejs 中的 Passport 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41624064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com