gpt4 book ai didi

javascript - 我的express.js和passport.js中间件都正常工作并且正在被调用,但是页面没有重定向

转载 作者:行者123 更新时间:2023-12-02 23:30:00 25 4
gpt4 key购买 nike

我目前正在开发一个 Node/快速服务器,我决定使用 Passport-local 与本地 MongoDB 服务器一起进行用户身份验证。我使用 html 表单中的 POST 方法来发送两个项目:电子邮件和密码(我更改了 LocalStrategy 实例中的 usernameField 项目)。使用 console.log,我看到了 Mongo 和 Passport 的所有正确且预期的行为。但是,页面永远不会使用 successRedirect 或 failureRedirect 进行重定向。看起来 html 页面 (Login.html) 刚刚刷新。有趣的是,根据我决定如何从表单发出 POST 请求,我会得到不同的行为。最初,我使用 jQuery 和 $('#id').submit() 方法在 '/students' 处调用 $.post 请求,并且观察到了上述行为。但是,当我摆脱这个脚本并用于发送请求时,没有调用任何中间件(再次,我使用 console.log 确认了这一点),并且页面立即重定向到我的 failureRedirect url,无论我是否输入了有效的表单中的数据。

注意:“学生”是我的 Mongoose 模型的名称,问题不在于此

我已经尝试过的事情:1. 在我的 Passport.authenticate 中使用自定义回调并使用 res.redirect。事实上,我在这个函数中放置了一个 console.log 来查看它是否被调用,确实如此。但 res.redirect 完全不起作用。2. 摆脱我的自定义 usernameField 和 passwordField 并仅使用默认值。我观察到完全相同的行为。3. 使用 jQuery .click() 方法而不是 .submit() 方法。我以为提交表单与刷新页面有关,但这不起作用。

我认为可能有帮助但我不知道如何实现:1.更改我所有服务器端Javascript的顺序(也许有些东西没有被正确调用)2.我在某处看到使用了passport.authorize而不是passport.authenticate

在 app.js 中

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

passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
(username, password, done) => {
console.log(username, password);
Student.findOne({ email: username, password:password }, function(err, user) {
console.log(user); //this works as expected
console.log(!user); //this works as expected
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}

if (user.password != password) {
return done(null, false, { message: 'Incorrect password.' });
}

return done(null, user);
});
}));

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

passport.deserializeUser(function(id, done) {
Student.findById(id, function(err, user) {
done(err, user);
});
});

app.post('/students', passport.authenticate('local', {
successRedirect:'/public/Schedule.html',
failureRedirect:'/'
}));

在Login.html的script标签中

$('#loginForm').submit(() => {
let currentUser = {
email: $('#email').val(),
password: $('#password').val()
}

checkForUser(currentUser);
});

function checkForUser(user) {
$.post('http://localhost:9000/students',user, (data) => {
console.log(data);
})
}

最佳答案

来自网页中 Javascript 的 Ajax 调用不会根据 http 响应自动重定向。自动重定向是指不直接从 Javascript 调用服务器的情况,例如单击链接、提交表单(不使用 Javascript)、在 URL 栏中输入 URL 等...

相反,当从 Javascript 发送请求时(正如您的请求所示),Javascript 会返回响应,并且该响应可供您的 Javascript 使用。如果您看到它是 302 并且想要重定向,那么您可以获取位置 header 并将 window.location 设置为该重定向 URL 以使页面重定向。

关于javascript - 我的express.js和passport.js中间件都正常工作并且正在被调用,但是页面没有重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56553845/

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