node.js - 无法使用快速会话将用户信息传递到不同的路线?
问题描述
所以我的登录帖子路由验证了用户并从数据库中获取用户信息。然后我想将其发送到重定向路线。我正在使用会话,但有关如何操作的教程和以前的问题要么不起作用,要么已被弃用。
这就是我正在做的获取我通过这一行保存在 req.session 中的用户信息
req.session = Users
然后我输入这个来验证我得到了用户信息
console.log(req.session)
它有效,我在服务器终端中看到了所有信息。
但是,一旦我尝试在重定向路由中传递信息,我就无法检索会话。
所以这是路由器端代码
router.post('/Login', async (req,res)=> {
try {
const Users = await User.findOne({ email:req.body.email}).exec()
const auth = await bcrypt.compare(req.body.password, Users.password)
if (auth){
req.session = Users;
res.redirect('./profile' )
}
else { res.send('invalid credentials')}
}
catch (err) {
console.log('error',err)
res.status(500).send('invalid credentials')
}
})
// Profile page
router.get(('/profile'), (req, res)=>
res.render('Projects/file.ejs', {info:req.session}
))
文件.ejs
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3>User info</h3>
<p><%= info %></p>
</body>
</html>
错误信息
error TypeError: req.session.touch is not a function
at ServerResponse.end (C:\Users\Moe\Desktop\Login Practice\node_modules\express-session\index.js:330:21)
at ServerResponse.redirect (C:\Users\Moe\Desktop\Login Practice\node_modules\express\lib\response.js:951:10)
at C:\Users\Moe\Desktop\Login Practice\routes\api\projects.js:46:6
第 46 行是
res.redirect('/profile)
有谁知道如何解决这一问题?
解决方案
您正在使用 覆盖请求对象上的整个会话属性req.session = Users
。相反,使用req.session.user = Users
使用时重命名Users
为. 返回单个对象。user
user.findOne
findOne
推荐阅读
- php - 内连接 MySQL 图像显示
- python - 子进程python读取输出
- node.js - 如何正确使用带 passport_ldapauth 的会话?
- elasticsearch - Mapper_parsing_exception :压缩器检测只能在某些 xcontent 字节或压缩的 xcontent 字节上调用
- python - 使用请求获取请求未返回主机标头
- jquery - 如何在 ASP.NET MVC 5 项目中使用 jquery-validation-unobtrusive 验证文件的大小?
- c# - 如何使用 AuthenticationMiddleware 和注入应用程序设置
- ios - 在自定义迁移策略中传递给模型迁移函数时,Core Data 实体中的 Int16 支持的枚举属性似乎具有不正确的值
- ethereum - 以太坊 Geth - 待处理交易
- android - 自定义 TextInputLayout 和 TextInputEditText