Passport.authenticate 无处重定向

Passport.authenticate redirects nowhere

我正在尝试学习如何使用 passport-local 及其文档,我可以做到这一点,但是当我提交表单时它不会重定向到任何站点

const express = require("express");
const router = express.Router();

const passport = require("passport");
const localStrategy = require("passport-local").Strategy;

const UserList = [{ email: "1@1", password: "1" }];

passport.use(new localStrategy(async (email, password, done) => {

    const thisUser = UserList.find(x => x.email = "email" && x.password == password);
    return done(null, thisUser)

}));

router.get('/signup', (req, res) => {
    res.render('auth/signup.hbs')
});

router.post('/signup', (req, res) => {
    passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/login'
    })
});

module.exports = router;

您忘记使用

初始化 passport
app.use(passport.initialize());

并使用

序列化用户
passport.serializeUser(function (user, done) {
         done(null, user);
     });

您可以在下面查看完整示例。我做了一个测试,它成功了。

var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var passport = require('passport');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var LocalStrategy = require('passport-local').Strategy;

app.use(morgan('dev')); // log tất cả request ra console log
app.use(cookieParser()); // đọc cookie (cần cho xác thực)
app.use(bodyParser()); // lấy thông tin từ html forms
app.set('view engine', 'ejs'); // cài đặt ejs là templating

app.use(passport.initialize());

const UserList = [{email: "1@1", password: "1"}];
passport.serializeUser(function (user, done) {
         done(null, user);
     });

passport.use('local-signup', new LocalStrategy({
            usernameField: 'email',
            passwordField: 'password',
            passReqToCallback: true // cho phép chúng ta gửi reqest lại hàm callback
        },
        function (req, email, password, done) {
            process.nextTick(function () {
                 const thisUser = UserList.find(x => x.email = "email" && x.password == password);
                return done(null, thisUser)
            });
        }));

//
// routes ======================================================================
app.get('/', function (req, res) {
        res.render('index.ejs'); // load the index.ejs file
    });
  
    app.get('/signup', function (req, res) {
        res.render('signup.ejs');
    });

    app.post('/signup', passport.authenticate('local-signup', {
        successRedirect: '/', 
        failureRedirect: '/signup', 
   
    }))

// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);