gpt4 book ai didi

node.js - LocalStrategy 函数从未被调用

转载 作者:太空宇宙 更新时间:2023-11-03 23:38:14 26 4
gpt4 key购买 nike

我尝试使用express4/passportjs设置一个简单的本地策略身份验证,但从未调用身份验证函数:这是我的代码

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
app.use(compress());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

/* AUTHENTIFICATION */

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


passport.serializeUser(function(user, done) {
done(null, user);
});

passport.deserializeUser(function(user, done) {
done(null, user);
});

passport.use(new LocalStrategy(
function(username, password, done) { //THIS FUNCTION IS NEVER CALLED
console.log("Local strategy");
}
));


app.post('/login', function(req, res) {
console.log("user : ", req.body.username);
console.log("password : ", req.body.password);
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' })
});

/* !AUTHENTIFICATION */

app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
app.use(express.static(path.join(__dirname, 'controllers')));
app.use(express.static(path.join(__dirname, 'modules')));
app.use('/', routes);
app.use('/users', users);

当我在/login 中发送发布请求时,我在日志中看到用户名和密码,但 password.authentificate 方法不执行任何操作。它应该调用 LocalStrategy 函数和 console.log('strategy'),但事实并非如此。

有人知道怎么解决吗?

谢谢

最佳答案

authenticate() 的函数签名是来自 here 的标准 Connect 中间件 .

因此应传递req、res、next的引用

所以你可以使用它作为路由中间件

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

或者

app.post('/login', function(req, res, next) {
passport.authenticate('local', { successRedirect: '/',
failureRedirect: '/login' })(req, res, next);
});

关于node.js - LocalStrategy 函数从未被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28608764/

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