护照 Session 无法序列化(错误的网关)

Passport Session Failed to serialize (Bad Gateway)

我正在使用以下依赖项:

  1. 快递session
  2. 护照
  3. passport-local
  4. passport-local-猫鼬

当我尝试注册用户时,他们 post 数据。数据被保存到数据库中,但它给出了一个错误的请求。此外,当我尝试在 Tweet.find() 中使用 req.user.id 时,它给出了未定义的,我也使用 console.log(req.user) 并且它给了我未定义的。并且一旦出现一两次未能序列化 session 的错误。有谁能够帮我。这是一些代码,如果代码太多,请提前致歉,因为我不确定代码的哪一部分很重要。

//-----------------------//Require---------------------
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const ejs = require("ejs");
const session = require("express-session");
const passport = require("passport");
const LocalStratagy= require("passport-local").Strategy;
const passportLocalMongoose = require("passport-local-mongoose");
const mongoose = require("mongoose");

//-----------------------//App.use---------------------

app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
}));
//-----------------------//Passport---------------------

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


//-----------------------//Mongoose---------------------
mongoose.connect('mongodb://localhost/Twitter', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useCreateIndex', true);
const tweetschema = new mongoose.Schema({
    username: String,
    password: String,
    tweets: String
});
//-----------------------//Schema Plgin---------------------

tweetschema.plugin(passportLocalMongoose);

//-----------------------//New Model---------------------

const Tweet = new mongoose.model("Tweet", tweetschema);

//-----------------------//Local Strategy-------------------
passport.use(new LocalStratagy(Tweet.authenticate()));

//-----------------------//Seralize Passport---------------------

passport.serializeUser(function(user, done) {
    console.log(user);
    done(null, user.id);
});

//-----------------------//Desarlize Passport---------------------
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

app.post("/tweets", bodyParser.urlencoded({extended: true}), (req, res)=>{
    const Gottweets= req.body.tweet;
    console.log(Gottweets);
    console.log(req.user);
   /*  Tweet.findById(req.tweet.id, (err, foundUser)=>{
        if(err){
            console.log(err);
            res.redirect("/tweets");
        }else{
            if(foundUser){
                foundUser.tweets = Gottweets;
                foundUser.save(()=>{
                    res.redirect("/");
                })
            }
            
        }
        
    })
     */
    


});

app.post("/regsiter",bodyParser.urlencoded({extended: true}), (req, res)=>{
    console.log(req.body.email);
    Tweet.register({username: req.body.email}, req.body.password, (err, user)=>{
        if(err){
            console.log(err);
            res.redirect("/regsiter");
        }else{
            if(user){
                passport.authenticate("local")(req, res, function(){
                    res.redirect("/regsiter");
                })
            }
        }
    })
});
<%- include('partials/header') %>
<form action="/regsiter" method="post" class="login">
    <label for="emial" class="email">
        Email
        <input type="email" name="email" id="email">
    </label>
    <label for="password">
        Password
        <input type="password" name="password" id="password">
    </label>
    <div class="soicalLogin">
        <a href="#" class="facebook">Facebook</a>
        <a href="#" class="google">Google</a>

    </div>
    
    <button type="submit">Register</button>
    

</form>

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

您可以尝试使用此示例重写您的 POST /register 端点

app.post("/register",bodyParser.urlencoded({extended: true}), (req, res, next) => {
    console.log(req.body.email);
    Tweet.register({username: req.body.email}, req.body.password, (err, user)=>{
        if(err){
            console.log(err);
            res.redirect("/regsiter");
            return;
        }
        if(!user){ // also handle the case where user is undefined
            return res.status(500).json({ yourMessage: 'error' });
        }
        next();
    })
}, passport.authenticate("local", { successRedirect: '/', failureRedirect: '/register' }));

重写给 passport.authenticate("local")

next 函数不是一个好主意

现在错误应该消失了,如果此代码示例不起作用,请告诉我。

希望对您有所帮助