我正在使用 MERN 堆疊創建一個 Web 應用程式,我想為其實作 google OAuth 和會話,為此我使用“express-session”和“passport.js”。一切似乎都按預期作業,但我得到了一個 error: req.isAuthenticated isn't function
. 此外, the value of req.user is "undefined"
cookie 正在生成并成功存盤在 MongoDB 中。我是節點和護照的新手,所以我無法找出問題所在。此外,先前針對同一錯誤提出的問題的解決方案對我不起作用。
這是錯誤
(node:10481) UnhandledPromiseRejectionWarning: TypeError: req.isAuthenticated is not a function
at addYear (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/controllers/years.js:15:18)
at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/layer.js:95:5)
at /media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:341:12)
at next (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:174:3)
at router (/media/test/DATA/Dev/full-stack/projects/budget-app-backend/node_modules/express/lib/router/index.js:47:12)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:10481) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:10481) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
我還添加了代碼以供參考。
server.js 中的代碼
const dotenv = require("dotenv");
dotenv.config();
const express = require("express");
const cors = require("cors");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const authRouter = require("./routes/auth");
const Info = require("./models/Info");
const Transaction = require("./models/Transactions");
const recordsRouter = require("./routes/recordsRouter");
const { User, userSchema } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const startDB = require("./models/db");
const app = express();
const PORT = process.env.PORT || 8000;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,POST,PUT,DELETE",
credentials: true,
})
);
app.use(
session({
secret: "some random string",
resave: false,
saveUninitialized: false,
store: MongoStore.create({
mongoUrl: "mongodb://0.0.0.0:37017/budgetDB",
}),
})
);
startDB();
app.use("/auth", authRouter);
app.use("/dashboard", recordsRouter);
app.use(passport.initialize());
app.use(passport.session());
require("./passport")(passport);
app.listen(PORT, () => {
console.log(`Server started listening on port ${PORT}.....`);
});
passport.js 中的代碼
const { User } = require("./models/Users");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
module.exports = function (passport) {
passport.serializeUser((user, done) => {
console.log(`From passport.js serializeUser: ${user}`);
return done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id, (err, user) => {
done(err, user);
});
});
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/google/callback",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
async (accessToken, refreshToken, profile, done) => {
const newUser = new User({
name: profile.displayName,
googleId: profile.id,
});
try {
const user = await User.findOne({ googleId: profile.id });
if (!user) {
user = await User.create(newUser);
}
return done(null, user);
} catch (err) {
console.log(`Error From 'passport.js': ${err}`);
return done(err);
}
}
)
);
};
auth.js 中的代碼
const router = require("express").Router();
const passport = require("passport");
const CLIENT_URL = "http://localhost:3000";
router.get("/login/failed", (req, res) => {
console.log(res);
res.status(401).json({
message: "login failed",
});
});
router.get("/logout", (req, res) => {
req.logout();
res.redirect(CLIENT_URL);
});
router.get("/google", passport.authenticate("google", { scope: ["profile"] }));
router.get(
"/google/callback",
passport.authenticate("google", {
failureRedirect: "/login/failed",
successRedirect: CLIENT_URL "/Dashboard",
})
);
module.exports = router;
用戶模型中的代碼
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
name: String,
googleId: String,
});
const User = mongoose.model("User", userSchema);
module.exports = { User, userSchema };
uj5u.com熱心網友回復:
中間件訂單很重要。把.use(passport...)
前面的.use(router...)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/453610.html
標籤:节点.js mongodb 表示 护照.js 快速会话