当前位置:网站首页>[node] theory + practice enables you to win sessions and cookies

[node] theory + practice enables you to win sessions and cookies

2022-06-22 09:20:00 Jdoit CW

Content

understand session、cookie
use node Server implementation session、cookie
Front end demonstration

1. cookie And session

cookie: A space opened up by the browser in the computer hard disk , It is mainly used for server-side data storage .

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

session: It's actually an object , Stored in memory on the server side , stay session Object can also store multiple pieces of data , Every piece of data has a sessionid As the only sign .

Verification diagram :

 Insert picture description here

2. node Server implementation

stay node.js We need the help of express-session Realization session function ., Portal :express-session

Specific operations inside the middleware

Add... To the request object session attribute ,session The value of is the object ,session The user information can be saved after the user logs in successfully , The method will be used internally when we go to session Generated when data is stored in the sessionId, Is the unique identification of the currently stored data , And then sessionId Stored on the client side cookie in . When the client accesses the server again , Method will get the data from the client cookie , And extract from it sessionId, And according to sessionId from cookie User information found in . At this point, the authentication is successful !

build node Server code A little ( Please refer to :node Server setup

2.1 First in the entry file (app.js) Write create session Middleware
app.use(session({
     // establish session middleware 
    secret: 'secret keys',
    resave: false,
    saveUninitialized: false,
    cookie: {
    
        maxAge: 24 * 60 * 60 * 1000 // session Expiration time 
    }
}))
2.2 Log in successfully , And when you log out, you should check the session To operate
const express = require('express');
const router = express.Router();
const dbConfig = require('../util/dbconfig.js'); //  Database connection pool 

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 //  Add user information to the request object 
            res.send({
    
                status: 200,
                msg: ' Login successful '
            })
        } else {
    
            res.send({
    
                status: 400,
                msg: ' Wrong user name or password '
            })
        }
    } else {
    
        res.send({
    
            status: 400,
            msg: ' The username does not exist '
        })
    }
})

//  Log out 
router.get('/loginout', (req, res) => {
    
    req.session.destroy(err => {
    
        if (err == null) {
    
            res.clearCookie('connect.sid'); //  Delete the corresponding... Of the client cookie,( Note that the value here is unique , It depends on the attribute name of the client )
            res.send({
     msg: ' Log out ', status: 200 })
        } else {
    
            res.send({
     msg: ' Exit failed ', status: 400 })
        }
    })
})

//  Determine whether the user is logged in 
router.get('/loginStatus', (req, res) => {
    
    if (req.session && req.session.username) {
     // provided that session There is information in 
        res.send('var isLogin = true')
    } else {
    
        res.send('var isLogin = false')
    }
})

module.exports = router

Be careful : For the database connection pool here, please refer to :mysql Connect

3. Actual demonstration

3.1 Verification effect display

 Insert picture description here

3.2 step

①: Create a static page on the server :login.html 、index.html
②: use ajax request Access the corresponding interface
③: Request the user status interface on the required page , Make sure the user is logged in

  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=" Sign in ">
    </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(' Wrong user name or password ') } } }) return false }) }) </script>
</body>

</html>

index.html

<!--  Determine login status  -->
<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:;"> Log out </a>
    <script> $('a').on('click', function() {
      $.ajax({
      url: '/users/loginout', success(res) {
      if (res.status == 200) {
      console.log(' Log out '); location.href = '/login.html' } } }) }) </script>
</body>

</html>

Be careful : Add status judgment to the required page , Ensure user identity

About authentication , More often I will use token, About token Use , May refer to :token verification

原网站

版权声明
本文为[Jdoit CW]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220844301446.html