gpt4 book ai didi

javascript - Passport JS 无法读取未定义的属性(读取 'initialize' )

转载 作者:行者123 更新时间:2023-12-03 08:14:04 24 4
gpt4 key购买 nike

实现 Passport.js 进行身份验证时遇到错误。 session 集合有数据解析,但是,我收到此错误:

TypeError: Cannot read properties of undefined (reading 'initialize')
at Authenticator.initialize (\server\node_modules\passport\lib\authenticator.js:130:26)
at Layer.handle [as handle_request] (\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (\server\node_modules\express\lib\router\index.js:317:13)
at \server\node_modules\express\lib\router\index.js:284:7
at Function.process_params (\server\node_modules\express\lib\router\index.js:335:12)
at next (\server\node_modules\express\lib\router\index.js:275:10)
at session (\server\node_modules\express-session\index.js:479:7)
at Layer.handle [as handle_request] (\server\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (\server\node_modules\express\lib\router\index.js:317:13)
at \server\node_modules\express\lib\router\index.js:284:7

我的index.js 文件包含以下内容:

// Route Variables
const loginRoute = require("./routes/api/login");

/*
==MIDDLEWARE==
*/
// Express Parsing Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// Passport Auth Middleware
require("./config/passport");

/*
==SESSION SETUP==
*/

const sessionStore = MongoStore.create({
mongoUrl: process.env.MONGO_URL,
});

app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: true,
store: sessionStore,
cookie: {
maxAge: 1000 * 60 * 60 * 24,
},
})
);

// Initialize Passport and Use Session for Serialize/Deserialization
app.use(passport.initialize);
app.use(passport.session());

/*
==ROUTES==
*/
// User Route
app.use("/api", loginRoute);

当路由到/api/login时,登录文件包含以下内容:

const router = require("express").Router();
var passport = require("passport");

router.post(
"/login",
passport.authenticate("local", {
failureRedirect: "/login",
successRedirect: "/dashboard",
})
);

module.exports = router;

最后,我的 Passport 中间件文件:

const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const bcrypt = require("bcrypt");
const User = require("../models/User");

const verifyCallback = (username, password, done) => {
User.findOne({ username: username })
.then((user) => {
if (!user) {
return done(null, false);
}

// Validate Password
bcrypt.compare(password, user.password).then((isMatch) => {
if (isMatch) {
return cb(null, user);
} else {
return cb(null, false);
}
});
})
.catch((err) => {
done(err);
});
};

const strategy = new LocalStrategy(verifyCallback);

passport.use(strategy);

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

passport.deserializeUser((userId, done) => {
User.findById(userId)
.then((user) => {
done(null, user);
})
.catch((err) => done(err));
});

这似乎是我不知道它来自何处或击中何处的错误之一。当点击登录表单的提交按钮时,它只会抛出错误。除此之外,它初始化得很好。我查看了 Passport.js 文档,一切都按其应有的顺序进行。

我的前端在点击提交按钮时调用此函数:

const handleOnSubmit = (e) => {
e.preventDefault();

login(data)
.then((response) => {
toast.success(response.data.message);
setData({ username: "", password: "" });
navigate("/dashboard");
})
.catch((err) => {
if (err.response) {
toast.error(err.response.data.message);
} else if (err.request) {
toast.error(err.request);
} else {
toast.error(err.message);
}
});
};

并且从我前端的loginAPI.js 文件调用登录函数,其中包含以下内容:


const instance = axios.create({
baseURL: "http://localhost:8000/api/",
timeout: 1000,
});

export async function login(data) {
if (!data.username || !data.password) {
return Promise.reject(new Error("Data is missing"));
}

return await instance.post("/login", data);
}

最佳答案

问题出在 index.js 中的这一行:

app.use(passport.initialize);

您应该调用函数initialize()属性initialize。像这样更改您的代码:

app.use(passport.initialize());

关于javascript - Passport JS 无法读取未定义的属性(读取 'initialize' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69982445/

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