gpt4 book ai didi

node.js - 使用 Passport-local-mongoose 的错误请求

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:00 25 4
gpt4 key购买 nike

我正在尝试使用passport、mongodb、mongoose、express 和passport-local-mongoose 插件构建对小型网络应用程序的身份验证。当我尝试登录用户时,收到错误请求。我能够注册用户并将数据获取到数据库中。

如何通过错误处理继续调试此问题? Passport 和 Passport 本地 Mongoose 的文档似乎很简单(而且我有点菜鸟)。

App.js

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

app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);

var User = require('./models/user.js')
passport.use(new LocalStrategy(User.authenticate()));

//passport.use(new LocalStrategy(UserSchema.authenticate()))
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

// Connect to Mongoose
mongoose.connect('mongodb://localhost/users')

注册路由(获取数据到数据库,但重定向失败)

// Register a user to the DB
router.post('/register', function(req, res, next){
let firstName = req.body.firstName
let lastName = req.body.lastName
let username = req.body.email
//let password = req.body.password
let homeAirport = req.body.homeAirport

User.register(new User ({
firstName: firstName,
lastName: lastName,
username: username,
homeAirport: homeAirport
}),
req.body.password, function(err, user) {
if (err) {
console.log(err)
return res.render('register', {
user: user
})
}
// both of these works
passport.authenticate('local', { failureRedirect: '/' }),
function(req, res, next) {
res.redirect('/');
}
})
})

登录路由(返回错误请求)

router.post('/login', passport.authenticate('local'), function(req, res) {
res.redirect('/');
});

用户架构

var mongoose = require('mongoose'),
Schema = mongoose.Schema,
passportLocalMongoose = require('passport-local-mongoose');

// Define the scheme
var User = new Schema ({
firstName: {
type: String,
index: true
},
lastName: {
type: String,
index: true
},
email: {
type: String,
index: true
},
homeAirport: {
type: String,
index: true
}
})

User.plugin(passportLocalMongoose)

module.exports = mongoose.model('User', User)

最佳答案

抱歉回复晚了!我也遇到过这样的问题。问题不在于 Passport 本地 Mongoose ,而在于 Passport 。它期望 http 请求包含用户名和密码字段。因此,如果您使用电子邮件进行注册,它会返回错误的请求。

要解决此问题,请更改 userNameField,如下所示

passport.use(new LocalStrategy({
usernameField: 'email',
},User.authenticate()));

希望有帮助

关于node.js - 使用 Passport-local-mongoose 的错误请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40677248/

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