我在后端有一个Express服务器,该服务器使用Passport.js进行身份验证。即使成功通过身份验证,当重定向到“ / about”,“ / login”或任何其他路径(所有这些路径都存在于前端)或什至未重定向时,Web浏览器中仍显示404错误。 只有当重定向到“ /”时,才会显示404。我将在下面添加相关的代码段。
users.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' }))
passportLocalStrategy.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;
这是发出请求(Vue.js)的前端javascript代码
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);
});
}
}