验证用户后,Passport.js不会重定向

时间:2017-10-14 02:35:27

标签: node.js redirect passport.js

我已经设置了来自passport.js的护照本地策略,以便我可以为我的应用注册和验证用户。

到目前为止,一切似乎都运行正常 - 网络请求通过正常,用户被创建并成功保存到数据库。

但是,passport.authenticate内的重定向似乎无法正常工作。

authRoutes.js:

const passport = require('passport');

module.exports = app => {
  app.post(
    '/register',
    passport.authenticate('local-signup', {
      successRedirect: '/',
      failureRedirect: '/'
    })
  );
};

passport.js:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongoose = require('mongoose');
const User = mongoose.model('users');

passport.serializeUser((user, done) => {
  console.log('serialize:', user.id);
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id).then(user => {
    console.log('deserialize:', user);
    done(null, user);
  });
});

// Local signup strategy
passport.use('local-signup', new LocalStrategy(
  {
    usernameField: 'email',
    passwordField: 'password',
    passReqToCallback: true
  },
  (req, email, password, done) => {
    console.log('req:', req.body);

    User.findOne({ 'local.email': email }, (err, user) => {
      console.log('error:', err);
      console.log('user:', user);
      if (err) { return done(err); }

      if (user) {
        return done(null, false, { message: 'That email already exists' })
      } else {
        new User({
          'local.email': email,
          'local.password': password
        }).save(err => {
          if (err) { throw err };
        }).then(user => {
          console.log('new user:', user);
          return done(null, user)
        });
      }
    });

  }
));

Github回购:https://github.com/drhectapus/Voting-App

更新:

我清理了这段代码,因为它使用了一系列回调和承诺:

new User({
  'local.email': email,
  'local.password': password
}).save(err => {
  if (err) { throw err };
}).then(user => {
  console.log('new user:', user);
  return done(null, user)
});

当我清理上面的代码时:

new User({
  'local.email': email,
  'local.password': password
}).save((err, user) => done(err, user));

它成功地将用户保存到数据库而没有任何错误,但仍然没有正确重定向。

然而,当我清理上面的代码时:

new User({
  'local.email': email,
  'local.password': password
})
.then(user => done(null, user))
.catch(err => done(err));

我收到以下控制台错误:

在浏览器控制台中:

POST http://localhost:3000/register 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
    at createError (createError.js:16)
    at settle (settle.js:18)
    at XMLHttpRequest.handleLoad (xhr.js:77)

在终端控制台中:

TypeError: (intermediate value).then is not a function
[0]     at User.findOne (/Users/Joseph/workspace/voting-app/services/passport.js:40:10)
[0]     at model.Query.<anonymous> (/Users/Joseph/workspace/voting-app/node_modules/mongoose/lib/model.js:3919:16)
[0]     at /Users/Joseph/workspace/voting-app/node_modules/kareem/index.js:273:21
[0]     at /Users/Joseph/workspace/voting-app/node_modules/kareem/index.js:131:16
[0]     at _combinedTickCallback (internal/process/next_tick.js:131:7)
[0]     at process._tickCallback (internal/process/next_tick.js:180:9)
[0] [nodemon] app crashed - waiting for file changes before starting...
[1] Proxy error: Could not proxy request /register from localhost:3000 to http://localhost:5000.
[1] See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
[1] 
[1] [HPM] Error occurred while trying to proxy request /register from localhost:3000 to http://localhost:5000 (ECONNRESET) (https://nodejs.org/api/errors.html#errors_common_system_errors)

1 个答案:

答案 0 :(得分:0)

这可能是由于:

new User({
  'local.email': email,
  'local.password': password
}).save(err => {
  if (err) { throw err };
}).then(user => {
  console.log('new user:', user);
  return done(null, user)
});

使用了一种奇怪的回调和承诺组合。

要么使用它(使用回调):

new User({
  'local.email': email,
  'local.password': password
}).save((err, user) => done(err, user));

或者这(使用承诺):

new User({
  'local.email': email,
  'local.password': password
}).save()
  .then(user => done(null, user))
  .catch(err => done(err));

编辑:您的编辑添加了相关的信息:XMLHttpRequest.handleLoad,因此您使用XMLHttpRequest(“AJAX”)来调用/register

在这种情况下,重定向作为AJAX请求流的一部分处理(对AJAX请求的响应将是重定向),并且它不会重定向AJAX请求的发生。

要实现更改页面,您需要处理该客户端。关于SO的答案有各种各样的问题,这些问题提供了如何实现这一点的想法: