For example to log
The basic implementation principle:
- The client through the account password
- Server receives the request parameters, generate the sessionId sessionId stored in a cookie to the client
- The next time a client requests to bring cookie, get a cookie server to verify the identity of sessionId
- Response user authentication by the client, which is a successful login
Instructions:
- node.js the need to use express-session achieve session function. Use npm instsall express-session download.
- Import module express-session const session = require ( 'express-session');
- Configuring session
app.use(session({ secret: 'secret key', //使用随机自定义字符串进行加密 saveUninitialized: false,//不保存未初始化的cookie,也就是未登录的cookie cookie: { maxAge: 24 * 60 * 60 * 1000 //设置cookie的过期时间为1天 activeDuration: 5* 60*1000, // 激活时间,比如设置为30分钟,那么只要30分钟内用户有服务器的交互,那么就会被重新激活。 } }))
4. Save the user information when the user logs
app.post('/login', async (req,res) => { const { email, password } = req.body; let user = await User.findOne({ email: email }); if (user.password == password){ req.session.user = user;//登录成功将用户信息存储到session下面 res.redirect('/home/'); }else{ res.render('login.art',{error:'账号或者密码错误'}) } })