javascript - 错误 : req#logout requires a callback function

标签 javascript express passport.js google-authentication

无法找到解决方案,尝试了所有方法,我只是使用 Passport 的新手。 错误:req#logout 需要回调函数 我之前已经对此进行了编码,但那次我没有收到任何错误,但这次不知道为什么我会收到这个,我也阅读了 Passport 文档并尝试了所有解决方案
提前致谢

<%- include('partials/header') %>

<header>
    <nav class="flex align-item-center">
        <div class="div-left">
            <img id="userimg" src="img/user.png" alt="logo">
        </div>
        <div class="div-right flex">
            <div style="font-size: 14px">
                <a href="/logout" role="button"> Logout</a>
            </div>
        </div>
    </nav>
</header>

<%- include('partials/footer') %>

js代码
require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require('express-session');
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require('mongoose-findorcreate');

const app = express();

app.use(express.static("public"));
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false
}))

app.use(passport.initialize());
app.use(passport.session());

mongoose.connect("#DB")

const accountsdata = new mongoose.Schema({
    email: String,
    password: String,
    googleId: String,
    facebookId: String,
    combo: String,
    date: String,
    price: String,
    accountemail: String

});

accountsdata.plugin(passportLocalMongoose);
accountsdata.plugin(findOrCreate);

const data = new mongoose.model("amazonprime", accountsdata);

passport.use(data.createStrategy());

passport.serializeUser(function (user, cb) {
    process.nextTick(function () {
        cb(null, { id: user.id, username: user.username });
    });
});

passport.deserializeUser(function (user, cb) {
    process.nextTick(function () {
        return cb(null, user);
    });
});

passport.use(new GoogleStrategy({
    clientID: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: "http://localhost:3000/auth/google/home",
    userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
},
    function (accessToken, refreshToken, profile, cb) {
        console.log(profile)
        data.findOrCreate({ googleId: profile.id }, function (err, user) {
            return cb(err, user);
        });
    }
));

app.get("/", (req, res) => {
    res.render("login");
});

app.get('/auth/google',
    passport.authenticate("google", { scope: ["profile"] })
);

app.get("/auth/google/home",
    passport.authenticate("google", { failureRedirect: "/" }),
    function (req, res) {

        res.redirect("/home");
    });

app.get("/signup", (req, res) => {
    res.render("signup");
});

app.get("/home", function (req, res) {
    if (req.isAuthenticated()) {
        res.render("home");

    } else {
        res.redirect("/");
    }
})

app.get("/logout", (req, res) => {
    req.logout();
    res.redirect("/");
});


app.post("/signup", (req, res) => {

    data.register({ username: req.body.username }, req.body.password, function (err, user) {
        if (err) {
            console.log(err);
            res.redirect("/signup");
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/home");
            })
        }
    })
})

app.post("/", function (req, res) {

    const user = new data({
        username: req.body.username,
        password: req.body.password
    })
    req.login(user, function (err) {
        if (err) {
            console.log(err);
        } else {
            passport.authenticate("local")(req, res, function () {
                res.redirect("/home")
            })
        }
    })
});

app.get("/logout", (req, res) => {
    req.logout();
    res.redirect("/");
});




app.listen(3000, function () {
    console.log("Server started on port 3000.");
});

错误
Error: req#logout requires a callback function
    at IncomingMessage.req.logout.req.logOut (E:\Web Development\Data Handler\node_modules\passport\lib\http\request.js:65:44)
    at E:\Web Development\Data Handler\app.js:105:9
    at Layer.handle [as handle_request] (E:\Web Development\Data Handler\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\Web Development\Data Handler\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (E:\Web Development\Data Handler\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (E:\Web Development\Data Handler\node_modules\express\lib\router\layer.js:95:5)
    at E:\Web Development\Data Handler\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (E:\Web Development\Data Handler\node_modules\express\lib\router\index.js:346:12)
    at next (E:\Web Development\Data Handler\node_modules\express\lib\router\index.js:280:10)
    at SessionStrategy.strategy.pass (E:\Web Development\Data Handler\node_modules\passport\lib\middleware\authenticate.js:346:9)

最佳答案

从 0.6.0 版开始(在撰写本文时仅在几天前发布),req.logout是异步的。这是避免 session 固定攻击的更大变化的一部分。
release announcement :

The other major change is that that req.logout() is now an asynchronous function, whereas previously it was synchronous. For instance, a logout route that was previously:

app.post('/logout', function(req, res, next) {
  req.logout();
  res.redirect('/');
});

should be modified to:

app.post('/logout', function(req, res, next) {
  req.logout(function(err) {
    if (err) { return next(err); }
    res.redirect('/');
  });
});

杰瑞德·汉森 mentioned文档还不是最新的:

It is necessary in order to improve the security of how sessions are managed during logout. Upgrading to 0.6.0 will require applications to pass a callback to req#logout. I'm still working on updating the docs and examples.

关于javascript - 错误 : req#logout requires a callback function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72336177/

相关文章:

javascript - 警报框中是否可以自定义按钮?

css - CSS 文件上的 ExpressJs 404

node.js - Socket.IO:推送到一组客户端

javascript - 如何将passport js配置放在一个公共(public)文件中

node.js - PassportJS 在用户通过身份验证后不重定向

javascript - 获取每个选定行的表格单元格值?

javascript - Angular Js-有没有办法动态生成也预先选择的复选框?

javascript - 将 javascript 函数的结果发送到 PHP

node.js - Express - 创建一个新的 View 引擎

node.js - Passport.js session 在重定向后丢失