express - 使用 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);
});
}
}
解决方案
推荐阅读
- jquery - 自动完成选择名称并将 id 插入隐藏输入
- unit-testing - 在 Jest 中模拟模块时如何断言默认导出函数被调用?
- sql - 计算内部连接的所有记录
- php - 如何根据房间类型和时间用户输入显示房间可用性?我必须加入 2 张桌子
- typescript - 创建一个 TypeScript 界面模板
- asp.net - 使用任何字段构建 URL
- python - Python One 热编码多元变量
- node.js - 12.0.0 上的 NODE_MODULE 函数中的本机插件编译错误,适用于 11.15.0
- excel - “编译错误”-“需要对象”VBA 代码
- list - 如何在Prolog中打印没有'[]'和','的列表中的内容