我不明白为什么我的api路由中未定义req.user。我有一个自定义中间件来设置名为auth的通行证,该通行证会初始化通行证和会话。
我制作了一个额外的中间件,只是看是否在api调用req.user定义之前就已经定义了。但是当我在api路由中需要它时,它是不确定的。
Server.js
...
server.use(cookieParser());
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({ extended: true }));
server.use(
session({
secret: process.env.COOKIE_SECRET,
resave: true,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
);
server.use(auth.initialize);
server.use(auth.session);
server.use(auth.setUser);
//API ROUTES
server.use("/user", require("./api/routes/user"));
server.use("/youtuber", require("./api/routes/youtuber"));
...
Auth.js
const passport = require("passport");
const LocalStrategy = require("passport-local").Strategy;
const UserModel = require("../api/models/user");
passport.use(
new LocalStrategy(
{ usernameField: "email" },
async (username, password, done) => {
try {
const user = await UserModel.findOne({ email: username }).exec();
if (!user) {
return done(null, false, { message: "Invalid username or password" });
}
const passwordOK = await user.comparePassword(password);
if (!passwordOK) {
return done(null, false, { message: "Invalid username or password" });
}
return done(null, user);
} catch (err) {
return done(err);
}
}
)
);
// eslint-disable-next-line no-underscore-dangle
passport.serializeUser((user, done) => {
console.log("serializing user: ");
console.log(user);
done(null, user._id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await UserModel.findById(id).exec();
return done(null, user);
} catch (err) {
return done(err);
}
});
module.exports = {
initialize: passport.initialize(),
session: passport.session(),
setUser: (req, res, next) => {
console.log(req.user, req.isAuthenticated()); //<-- HERE IT IS DEFINED
return next();
}
};
Api用户/ checkLogin
function isAuthenticated(req, res, next) {
if (req.isAuthenticated()) return next();
else
return res.status(401).json({
error: "User not authenticated"
});
}
...
router.get("/checklogin", isAuthenticated, (req, res, next) => {
res.status(200).json({
message: "User logged in correctly",
redirect: "/dashboard"
});
});