我一辈子都搞不清楚我做错了什么。我对passport和js都很陌生,但任何帮助都将不胜感激!每次我试图运行时,我得到的authenticate不是一个函数,然后如果我在htmlRoutes.js中需要passport,我得到的findOne不是一个函数。非常困惑
这是我的护照,js
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const User = require("../routes/htmlRoutes");
passport.use(
new LocalStrategy({ usernameField: "email" }, function (
email,
password,
done
) {
User.findOne({ email: email }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: "Incorrect Email..." });
}
if (!user.validPassword(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) {
User.findById(id, function (err, user) {
done(err, user);
});
});
module.exports = passport;
我的架构
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
first_name: {
type: String,
required: true,
},
last_name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
});
module.exports = mongoose.model("User", userSchema);
My htmlRoutes.js.在这里,如果我将passport更改为require(“passport”),我会丢失验证错误,但这样做对我来说没有任何意义
const express = require("express");
const Router = express.Router();
const User = require("../models/User");
const passport = require("../config/passport");
Router.get("/", (req, res) => {
res.render("index");
});
Router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/dashboard",
failureRedirect: "/login",
failureFlash: true,
})
);
Router.get("/dashboard", (req, res) => {
res.render("dashboard");
});
Router.post("/new/users", (req, res) => {
User.create({
first_name: req.body.first_name,
last_name: req.body.last_name,
email: req.body.email,
password: req.body.password,
}).then((data) => {
res.send(data);
});
});
module.exports = Router;
1条答案
按热度按时间xpszyzbs1#
有几件事我能看出来。
1.您没有将usercollectionSchema导入
passport
配置,而是导入导出路由器的userRoutes.js
,路由器肯定不包含findOne()
函数。1.其次,您可以继续在路由文件中使用
require('passport')
。我只是把需要修改的部分写出来,其他的都是显而易见的。
在您的passport.js文件中:
在userRoutes.js文件中: