使用passport-local-mongoose的错误请求

时间:2016-11-18 12:32:36

标签: node.js mongodb mongoose passport-local passport.js

我正在尝试使用passport,mongodb,mongoose,express和passport-local-mongoose插件为小型webapp构建身份验证。我在尝试登录用户时返回bad request。我能够注册用户并将数据输入数据库。

如何通过错误处理继续调试?护照和护照本地猫鼬的文件似乎很轻(我有点像菜鸟)。

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)

2 个答案:

答案 0 :(得分:4)

很抱歉迟到的回复!我也遇到过像这样的问题。问题不是护照本地猫鼬,而是护照。它希望http请求包含字段用户名和密码。因此,如果您使用电子邮件进行注册,则会响应错误的请求。

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

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

希望它有助于

答案 1 :(得分:0)

我还必须将其添加到架构中,如下所示:

userSchema.plugin(passportLocalMongoose, {
usernameField : "email"});