繁体   English   中英

我的express.js和passport.js中间件都可以正常工作并被调用,但是页面未重定向

[英]My express.js and passport.js middleware are all working and are being called, but the page does not redirect

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

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

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

我认为可能会有所帮助,但我不知道如何实现:1.更改所有服务器端Javascript的顺序(可能未正确调用某些内容)2.我看到某个地方使用了password.authorize代替了passport 。认证

在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的脚本标签中

$('#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等。

相反,当从Java脚本发送请求时(看起来像是Java脚本),Java脚本会返回响应,并且该响应可用于Java脚本。 如果您看到它是302并且要重定向,则获取位置标头并将window.location设置为该重定向URL,以使页面进行重定向。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM