首页 > 解决方案 > 使用 Passport.js 成功验证后出现 404 错误,除非重定向到“/”

问题描述

我在后端有一个 Express 服务器,它使用 Passport.js 进行身份验证。即使成功通过身份验证,当重定向到“/about”、“/login”或任何其他路径(所有这些路径都存在于前端)时,甚至在不重定向时,浏览器中也会显示 404 错误。唯一不显示 404 的情况是重定向到“/”。我将在下面包含相关的代码片段。

用户.js

router.post('/api/login', function(req, res, next) {
  passport.authenticate('local', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { return res.redirect('/login'); }
    req.logIn(user, function(err) {
      if (err) { return next(err); }
      // res.statusCode is still 200 here!!!!!!!!
      return res.redirect('/about');
    });
  })(req, res, next);
})

替代users.js(有同样的问题)

router.post('/api/login',
  passport.authenticate('local', { successRedirect: '/about',
                                   failureRedirect: '/login' }))

护照LocalStrategy.js

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

const init = require('./passportSessionConfig');
const knex = require('../db/connection');
const authUtils = require('./utils')

init();

passport.use(new LocalStrategy({
  usernameField: 'email',
  passwordField: 'password',
},
function (username, password, done) {
  // check to see if the username exists
  knex('users')
  .where({ 'email': username })
  .orWhere({ username })
  .first()
  .then((results) => {
    if (!results) return done(null, false);
    if (!authUtils.comparePass(password, results.password)) {
      return done(null, false);
    } else return done(null, results);
  })
  .catch((err) => { return done(err); });
}));

module.exports = passport;

这是发出请求的前端 javascript 代码 (Vue.js)

methods: {
  login: function(e) {
    e.preventDefault();
    let data = {
      email: this.email,
      password: this.password,
      returnTo: window.location.pathname
    };
    this.axios
      .post("/api/login", data)
      .then(response => {
        console.log("Logged in");
        this.$router.push("/about");
      })
      .catch(errors => {
        console.log("Cannot log in");
        console.log(errors);
      });
  }
}

这是来自网络浏览器的 404 错误 这是来自网络浏览器的 404 错误

标签: expressvue.jspassport.jspassport-local

解决方案


推荐阅读