Javascript req.session.passport为空:req.user未定义

Javascript req.session.passport为空:req.user未定义,javascript,node.js,session,cookies,express,Javascript,Node.js,Session,Cookies,Express,我以前也问过类似的问题,但我注意到它在Javascript部分。 对于现在可能出现的问题,我也有更具体的想法 基本上,req.session.passport在我的日志中是空的。每当我开始在我的站点上导航时,req.user就会变得未定义,因为会话中不再有Passport的登录用户 我想知道是否有人知道如何解决这个问题?也许这只是Passport配置中的一个错误,或者整个Express设置中的一个错误 App.js: var express = require("express"), b

我以前也问过类似的问题,但我注意到它在Javascript部分。 对于现在可能出现的问题,我也有更具体的想法

基本上,req.session.passport在我的日志中是空的。每当我开始在我的站点上导航时,req.user就会变得未定义,因为会话中不再有Passport的登录用户

我想知道是否有人知道如何解决这个问题?也许这只是Passport配置中的一个错误,或者整个Express设置中的一个错误

App.js:

var express = require("express"),
    bodyParser = require("body-parser"),
    mongodb = require("mongodb"),
    mongoose = require("mongoose"),
    uriUtil = require("mongodb-uri"),
    morgan = require("morgan"),
    session = require("express-session"),
    passport = require("passport"),
    flash = require("connect-flash"),
    ip = "hidden",
    port = process.env.PORT || 80

var app = express()
app.disable("x-powered-by")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))

app.use(morgan("dev")); // log every request to the console

// required for passport
app.use(session({
    secret: "hidden",
    key: 'asdasdasd', 
    cookie: { maxAge: 60000, secure: false },
    resave: true,
    saveUninitialized: false
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session

app.set("view engine", "jade")
app.use(express.static(__dirname + "/views"))

require("./includes/passport")(passport)
require("./includes/subject")
require("./includes/user")
Passport.js:

var LocalStrategy = require("passport-local").Strategy,
    User = require("./user"),
    bCrypt = require('bcrypt-nodejs')

module.exports = function(passport) {

    // used to serialize the user for the session
    passport.serializeUser(function(user, done) {
        done(null, user._id);
    });

    // used to deserialize the user
    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });

    // =========================================================================
    // LOCAL SIGNUP ============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called "local"

    passport.use('signup', new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : "email",
        passwordField : "password",
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) {

        // asynchronous
        // User.findOne wont fire unless data is sent back
        process.nextTick(function() {

            // find a user whose email is the same as the forms email
            // we are checking to see if the user trying to login already exists
            User.findOne({ "email" :  email }, function(err, user) {
                // if there are any errors, return the error
                if (err)
                    return done(err);

                // check to see if theres already a user with that email
                if (user) {
                    return done(null, false, req.flash("message", "Dit e-mail-adres is al bezet"));
                } else {

                    // if there is no user with that email
                    // create the user
                    var newUser = new User();

                    // set the user's local credentials
                    newUser.email = email;
                    newUser.password = createHash(password);
                    newUser.firstname = req.param('firstname');
                    newUser.lastname = req.param('surname');
                    newUser.year = parseInt(req.param('year'));
                    newUser.study = req.param('study');
                    newUser.courses = req.param('courses');
                    newUser.phone = req.param('phone');
                    newUser.availability = req.param('availability');
                    newUser.description = req.param('descText');

                    // save the user
                    newUser.save(function(err) {
                        if (err)
                            throw err;
                        return done(null, newUser);
                    });
                }

            });    

        });
    }));

    // =========================================================================
    // LOCAL LOGIN =============================================================
    // =========================================================================
    // we are using named strategies since we have one for login and one for signup
    // by default, if there was no name, it would just be called 'local'

    passport.use("login", new LocalStrategy({
        // by default, local strategy uses username and password, we will override with email
        usernameField : "email",
        passwordField : "password",
        passReqToCallback : true // allows us to pass back the entire request to the callback
    },
    function(req, email, password, done) { // callback with email and password from our form

        // find a user whose email is the same as the forms email
        // we are checking to see if the user trying to login already exists
        User.findOne({ "email" :  email }, function(err, user) {

            // if there are any errors, return the error before anything else
            if (err)
                return done(err);

            // if no user is found, return the message
            if (!user) {
                console.log('No user found with email ' + email)
                return done(null, false, req.flash('message', 'Gebruiker niet gevonden')); // req.flash is the way to set flashdata using connect-flash
            }

            if (!isValidPassword(user, password)){
                console.log('Incorrect Password');
                return done(null, false, req.flash('message', 'Onjuist wachtwoord')); // redirect back to login page
            }

            // all is well, return successful user
            return done(null, user);
        });

    }));

    var isValidPassword = function(user, password){
        return bCrypt.compareSync(password, user.password);
    }

    // Generates hash using bCrypt
    var createHash = function(password){
        return bCrypt.hashSync(password, bCrypt.genSaltSync(10), null);
    }

};
路线:

api.post("/signup", passport.authenticate("signup", {
    successRedirect: "/profile",
    failureRedirect: "/",
    failureFlash: true
}))

api.post("/login", passport.authenticate("login", {
    successRedirect: "/profile",
    failureRedirect: "/login"//,
    failureFlash: true
}))

router.get("/", function(req, res) {
    // serve index.html

    res.render("index", {
        title: 'Home',
        user: req.user,
        message: req.flash("message") 
    })
})
它在登录后直接访问的页面上工作,我对该页面的控制如下:

router.get("/profile", isLoggedIn, function(req, res) {
    res.render("profile", {
        title: 'Gebruikersprofiel van ' + req.user.firstname + " " + req.user.lastname,
        user: req.user // get the user out of session and pass to template
    })
})
function isLoggedIn(req, res, next) {
    console.log(req.session)
    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next()

    // if they aren't redirect them to the home page
    res.redirect("/login")
}
到目前为止,我已经尝试添加中间件将req.user添加到req.session,并在登录帖子中做了同样的事情。此外,我还尝试更改在app.js中初始化中间件的顺序。我正在使用新的express会话版本,没有CookieParser,因为我读到不再需要CookieParser


如果有人能以任何方式帮助我,我将不胜感激!和其他人一样,我也被困了一段时间。

问题不在于我在设置会话或Passport时做错了什么,而在于我的链接。 我在某个地方读到有人无意中在多个域中工作,他的平台显然是多服务器的,这让我今天早上查看了我的链接

显然,我是用www.前缀链接到我的网站的,但是会话是在URL前面没有www.的地方初始化的。我在饼干里看到了这个。
因此,解决方案是通过网站进行一致的链接,无论是在哪里都加上www.前缀。

问题不在于我在设置会话或Passport时做错了什么,而在于我的链接。 我在某个地方读到有人无意中在多个域中工作,他的平台显然是多服务器的,这让我今天早上查看了我的链接

显然,我是用www.前缀链接到我的网站的,但是会话是在URL前面没有www.的地方初始化的。我在饼干里看到了这个。
因此,解决方案是,在网站上始终保持链接,无论是在任何地方都有www.前缀,还是在任何地方都没有前缀。

你能检查一下这是否是你的问题吗?这不是,尽管它确实解决了我的另一个问题。你能检查一下这是否是你的问题吗?这不是,尽管它确实解决了我的另一个问题。