如何在Express Session中显示登录用户名并实现用户信息管理
问题解决:用户信息展示与资料管理功能实现
一、修复Dashboard用户信息展示问题
1. 登录/注册时存入用户信息到Session
你当前的代码只在Session中标记了isAuth,没有存储用户的具体信息,这就是req.session.username无法获取的原因。修改登录和注册路由,将用户关键信息存入Session:
登录路由修改
app.post("/login", async(req,res)=>{ const {email , password} = req.body; const user = await UserModel.findOne({email}); if (!user){ return res.redirect("/login"); } const isMatch = await bcrypt.compare(password , user.password); if(!isMatch){ return res.redirect("/login"); } // 存入用户信息到Session req.session.isAuth = true; req.session.user = { username: user.username, email: user.email, id: user._id }; res.redirect("/dashboard"); });
注册路由修改
app.post("/register", async (req,res)=>{ const {username , email , password } = req.body; let user = await UserModel.findOne({email}); if (user){ return res.redirect("/register"); } const hashPsw = await bcrypt.hash(password,12); user = new UserModel({ username, email, password:hashPsw }); await user.save(); // 添加await确保用户数据保存完成 // 存入用户信息到Session req.session.isAuth = true; req.session.user = { username: user.username, email: user.email, id: user._id }; res.redirect("/dashboard"); });
2. Dashboard路由传递用户信息到模板
修改Dashboard路由,将Session中的用户信息传递给EJS模板:
app.get("/dashboard", isAuth , (req,res)=>{ const userInfo = req.session.user; res.render("dashboard", { user: userInfo }); });
3. 在dashboard.ejs中展示信息
直接使用模板变量渲染用户数据:
<!DOCTYPE html> <html> <head> <title>用户控制台</title> </head> <body> <h2>欢迎回来,<%= user.username %>!</h2> <div class="user-info"> <p>绑定邮箱:<%= user.email %></p> </div> <form action="/logout" method="POST"> <button type="submit">退出登录</button> </form> </body> </html>
二、实现用户资料管理功能
1. 添加按用户名查询资料的路由
新增路由支持通过用户名获取用户资料(可限制仅本人访问):
// 用户资料页面路由 app.get("/profile/:username", isAuth, async (req, res) => { const targetUsername = req.params.username; // 可选:限制仅登录用户可查看自己的资料 if (req.session.user.username !== targetUsername) { return res.status(403).send("无权限访问该资料"); } try { // 查询用户并排除密码字段 const user = await UserModel.findOne({ username: targetUsername }).select("-password"); if (!user) { return res.status(404).send("用户不存在"); } res.render("profile", { user }); } catch (err) { console.error(err); res.status(500).send("服务器错误"); } });
2. 创建profile.ejs模板
<!DOCTYPE html> <html> <head> <title><%= user.username %>的个人资料</title> </head> <body> <h1><%= user.username %>的个人资料</h1> <ul> <li>邮箱:<%= user.email %></li> <li>注册时间:<%= user.createdAt.toLocaleString() %></li> <!-- 可根据UserSchema添加更多字段 --> </ul> <a href="/dashboard">返回控制台</a> </body> </html>
三、补充说明
- 确保你的UserModel包含必要字段(models/user.js示例):
const mongoose = require("mongoose"); const userSchema = new mongoose.Schema({ username: { type: String, required: true, unique: true }, email: { type: String, required: true, unique: true }, password: { type: String, required: true }, createdAt: { type: Date, default: Date.now } }); module.exports = mongoose.model("User", userSchema);
- 生产环境中不要硬编码Session的
secret,建议通过环境变量配置。
内容的提问来源于stack exchange,提问作者ARAVINTH S 20ISR004
相关产品推荐
相关产品推荐

