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

时间:2021-11-12 21:53:33

I've set up a passport local strategy from passport.js so that I can register and authenticate users for my app.

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

Up till now everything seems to be working fine - network requests go through fine and users are created and succesfully saved to the DB.

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

However, the redirects within the passport.authenticate don't seem to be working.

但是,passport.authenticate中的重定向似乎不起作用。

authRoutes.js:

authRoutes.js:

const passport = require('passport');

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

passport.js:

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 repo: https://github.com/drhectapus/Voting-App

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

UPDATE:

更新:

I cleaned up this bit of code because it uses a mix of callbacks and promises:

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

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

When I clean up the above code to this:

当我清理上面的代码时:

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

It successfully saves the user to the DB with no errors, but still doesn't redirect properly.

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

However, when I cleaned up the above code to this:

但是,当我清理上面的代码时:

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

I get the following console errors:

我收到以下控制台错误:

In browser console:

在浏览器控制台:

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)

In terminal console:

在终端控制台中:

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 个解决方案

#1


0  

It's probably caused by this:

这可能是由于:

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

Which uses a strange mix of callbacks and promises.

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

Either use this (using a callback):

使用它(使用回调):

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

Or this (using promises):

或者这个(使用承诺):

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

EDIT: your edit added this relevant piece of information: XMLHttpRequest.handleLoad, so you're using XMLHttpRequest ("AJAX") to call /register.

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

In that case, redirects are handled as part of the AJAX request flow (the response to the AJAX request will be the redirect), and it won't redirect the page on which the AJAX request occurs.

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

To implement changing the page, you need to handle that client-side. There are various questions with answers on SO that provide an idea on how that could be implemented:

要实现更改页面,您需要处理该客户端。关于SO的答案有各种各样的问题,可以提供有关如何实施的答案:

#1


0  

It's probably caused by this:

这可能是由于:

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

Which uses a strange mix of callbacks and promises.

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

Either use this (using a callback):

使用它(使用回调):

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

Or this (using promises):

或者这个(使用承诺):

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

EDIT: your edit added this relevant piece of information: XMLHttpRequest.handleLoad, so you're using XMLHttpRequest ("AJAX") to call /register.

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

In that case, redirects are handled as part of the AJAX request flow (the response to the AJAX request will be the redirect), and it won't redirect the page on which the AJAX request occurs.

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

To implement changing the page, you need to handle that client-side. There are various questions with answers on SO that provide an idea on how that could be implemented:

要实现更改页面,您需要处理该客户端。关于SO的答案有各种各样的问题,可以提供有关如何实施的答案: