所以我的登錄后路由驗證用戶并從資料庫中獲取用戶資訊。我想然后將其發送到重定向路由。我正在使用會話,但有關如何執行此操作的教程和以前的問題要么不起作用,要么已棄用。
這就是我通過這一行獲取我在 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)
有誰知道如何解決這一問題?
uj5u.com熱心網友回復:
您正在使用 覆寫請求物件上的整個會話屬性req.session = Users。相反,使用req.session.user = Users
使用時重命名Users為. 回傳單個物件。useruser.findOnefindOne
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/312459.html
