[Node] Theory + practice allows you to win session and cookie

content

Understand session and cookie,
use node server to realize session and cookie
front-end practical demonstration

1. cookie与session

Cookie : A space opened up by the browser in the computer hard disk, mainly for the server to store data.

  • The data in the cookie is distinguished in the form of a domain name.
  • The data in the cookie has an expiration time, and the data will be automatically deleted by the browser after the time expires.
  • The data in the cookie will be automatically sent to the server with the request.

session : actually an object, stored in the memory on the server side, multiple pieces of data can also be stored in the session object, and each piece of data has a sessionid as a unique identifier.

Verification diagram:

Insert picture description here

2. Node server implementation

In node.js, you need to use express-session to realize the session function. , Portal: express-session

Specific internal operations of middleware

Add the session attribute to the request object. The value of the session is the object. The session can save user information after the user logs in successfully. The method internally generates the sessionId when we store data in the session object, which is the unique identifier of the currently stored data, and then sets the sessionId Stored in a cookie on the client. When the client accesses the server again, the method will get the cookie from the client, extract the sessionId from it, and find the user information from the cookie based on the sessionId. At this time, the authentication is successful!

The code for building a node server is slightly (for details, please refer to: node server building )

2.1 First, write the middleware that creates the session in the entry file (app.js)
app.use(session({
    
     //创建session中间件
    secret: 'secret keys',
    resave: false,
    saveUninitialized: false,
    cookie: {
    
    
        maxAge: 24 * 60 * 60 * 1000 // session过期时间
    }
}))
2.2 The session must be operated upon successful login and when logging out
const express = require('express');
const router = express.Router();
const dbConfig = require('../util/dbconfig.js'); // 数据库连接池

router.post('/login', async(req, res) => {
    
    
    const {
    
     username, password } = req.body;
    let sql = 'select password from test where username=?';
    let sqlArr = [username];
    let result = await dbConfig.sysqlConnect(sql, sqlArr);
    if (result.length) {
    
    
        if (password === result[0].password) {
    
    
            req.session.username = username // 为请求对象添加用户信息
            res.send({
    
    
                status: 200,
                msg: '登录成功'
            })
        } else {
    
    
            res.send({
    
    
                status: 400,
                msg: '用户名或密码错误'
            })
        }
    } else {
    
    
        res.send({
    
    
            status: 400,
            msg: '用户名不存在'
        })
    }
})

// 退出登录
router.get('/loginout', (req, res) => {
    
    
    req.session.destroy(err => {
    
    
        if (err == null) {
    
    
            res.clearCookie('connect.sid'); // 删除客户端对应的cookie,(注意这里的值怒唯一,根据客户端的属性名而定)
            res.send({
    
     msg: '退出登录', status: 200 })
        } else {
    
    
            res.send({
    
     msg: '退出失败', status: 400 })
        }
    })
})

// 判断用户是否登录
router.get('/loginStatus', (req, res) => {
    
    
    if (req.session && req.session.username) {
    
     //若果session中存在信息
        res.send('var isLogin = true')
    } else {
    
    
        res.send('var isLogin = false')
    }
})

module.exports = router

Note : The database connection pool here can refer to: mysql connection

3. Practical demonstration

3.1 Verification effect display

Insert picture description here

3.2 Step

①: Create static pages on the server: login.html, index.html
②: Use ajax to request access to the corresponding interface
③: Request the user status interface on the required page to ensure that the user is in the login state

  1. login.html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/jquery.min.js"></script>
    <title>Document</title>
</head>

<body>
    <form id="loginForm">
        <input type="text" name="username" id="">
        <input type="password" name="password" id="">
        <input type="submit" value="登录">
    </form>
    <script>
        $(function() {
     
     
            $('#loginForm').on('submit', function() {
     
     
                const formdata = $(this).serialize();
                $.ajax({
     
     
                    url: '/users/login',
                    type: 'post',
                    data: formdata,
                    success(res) {
     
     
                        if (res.status == 200) {
     
     
                            location.href = '/index.html'
                        } else {
     
     
                            alert('用户名或密码错误')
                        }
                    }
                })
                return false
            })
        })
    </script>
</body>

</html>

index.html

<!-- 判断登录状态 -->
<script src="/users/loginStatus"></script>
<script>
    if (!isLogin) location.href = '/login.html'
</script>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/jquery.min.js"></script>
    <title>Document</title>
    <style>
        a {
     
     
            text-decoration: none;
            font-size: 30px;
            color: hotpink;
        }
    </style>
</head>

<body>
    <h1>welcome to index</h1>
    <a href="javascript:;">退出登录</a>
    <script>
        $('a').on('click', function() {
     
     
            $.ajax({
     
     
                url: '/users/loginout',
                success(res) {
     
     
                    if (res.status == 200) {
     
     
                        console.log('退出登录');
                        location.href = '/login.html'
                    }
                }
            })
        })
    </script>
</body>

</html>

Note : Add status judgment on the required page to ensure user identity

Regarding identity verification, tokens are used more often. Regarding the use of tokens, please refer to: token verification

Guess you like

Origin blog.csdn.net/cwq521o/article/details/107669660