NodeJS,获取路由内登录用户的用户名

问题描述 投票:0回答:2

我正在接触 NodeJS,并观看了一些视频教程来制作东西,以了解 NodeJS 和 Express。由于解释很少,它更多地变成了复制,所以尝试用我学到的东西来制作我自己的东西等等。

使用 PassportJS、ExpressJs 和 Mongoose 制作一个简单的登录功能。 登录和其他内容可以正常工作,如果我使用以下命令在主 app.js 中定义它,我可以获取当前登录用户的用户名并显示它:

app.get("/stuff", (req,res) => {
    res.render("stuff.html", {username:req.user.username});
});

现在,如果我想通过使用路由器来使其变得漂亮和结构化,我无法让它工作。它会抛出错误,指出

username
未定义,导致页面无法呈现。如果我不传递任何变量或使用我知道可以工作的变量,则路由器本身可以工作(例如
var x = "Hello"; res.render … {msg:x});
)。

处理路线的

app.js
的一部分:

var stuff = require("./routes/stuff");
app.use("/stuff", stuff);

module.exports.app;

我已经尝试过

cont x = require("…")
基本上是这个
app.js
文件中
stuff.js
中的所有内容,但无济于事,因此删除了除快速+路线之外的所有内容以重新开始。

如何将

app.js
中工作的用户名传递到路由文件中?如果可能的话,最好使用
app.get("*")…
或其他东西自动对每个页面执行此操作。

整个

stuff.js

/* Routes */
const express = require("express");
const router = express.Router();

/* Stuff */
router.get("/", function(req, res, next) {
    res.render("stuff.html", {username:req.user.username});
    console.log(req.user.username);
    next();
});

/* Bottom */
module.exports = router;

app.js
的登录部分:

app.post('/login',
    passport.authenticate('local', 
        {
            successRedirect: '/dashboard',
            failureRedirect: '/login',
            failureFlash: 'Wrong login'
        }
), function(req,res) {
        console.log("Hello " + req.user.username);
});

passport.serializeUser(function(user,done) {
    done(null, user.id);
});
passport.deserializeUser(function(id,done) {
    User.getUserById(id, function(err, user) {
        done(err,user);
    });
});

passport.use(new LocalStrategy(function(username,password,callback) {
    User.getUserByUsername(username, function(err,user) {
        if(err) throw err;
        if(!user) {
            return callback(null, false, {msg: "shit"});
        }

        User.comparePassword(password, user.password, function(err,isMatch) {
            if(err) return callback(err);
            if(isMatch) {
                return callback(null, user);
            } else {
                return callback(null, false, {msg:"Something"});
            }
        });
    });
}));

用于处理注册新用户的

users.js
文件(如果相关):

const mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/users");
const db = mongoose.connection;
mongoose.Promise = global.Promise;
const bcrypt = require("bcryptjs");

/* Data schema */
const userSchema = mongoose.Schema({
    name: {
        type: String
    },
    username: {
        type: String,
        index: true
    },
    password: {
        type: String
    },
    email: {
        type: String
    }
});

var User = module.exports = mongoose.model("User", userSchema);

module.exports.createUser = function(newUser, callback) {
    bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash(newUser.password, salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

module.exports.getUserById = function(id, callback) {
    User.findById(id, callback);
}

module.exports.getUserByUsername = function(username, callback) {
    var query = {username: username};
    User.findOne(query, callback);
}

module.exports.comparePassword = function(testPw, hash, callback) {
    bcrypt.compare(testPw, hash, function(err,isMatch) {
            callback(null,isMatch);
    });
}
node.js express mongoose passport.js body-parser
2个回答
0
投票

据我了解,您正在尝试将您的用户名传递到最好的每个文件,包括您的路由器文件。我为此所做的是使用 app.js 中的中间件来传递每个页面。或者您也可以简单地在其他页面中实现护照实施,我猜这可能毫无用处。

app.use(function(req,res,next){
  res.locals.currentUser=req.user
  next()
}

然后,当您尝试渲染时,您可以在每个页面中使用您的 currentUser 。


0
投票

我遇到了同样的问题,可能是在遵循相同的教程之后...... 我发现app.js中你需要的函数是:

app.get('*', function(req, res,next){
    res.locals.user = req.user || null;
    next();
})

它应该已经在 app.js 中了。现在,在所有其他页面中,您应该能够使用 req.user.username

© www.soinside.com 2019 - 2024. All rights reserved.