The client stores cookie + localStorage + sessionStorage and the server stores cookie + session

Table of contents

client storage

1.localStorage

1. Store data through localStorage.setItem(key, value)

2. Characteristics of localStorage storage

1. Store data through localStorage and save it permanently as long as it is not cleared.

2. Storage size: about 5M

3. Get the stored data through localStorage.getItem(key)

4. Clear a certain data stored in localStorage through localStorage.removeItem(key)

5. Clear all data stored in localStorage through localStorage.clear()

2.sessionStorage

1. Store data through sessionStorage.setItem(key, value)

2. Get the stored data through sessionStorage.getItem(key)

3. Features of sessionStorage storage

1.sessionStorage is not only limited to the same source, but also to the same window (the data stored in sessionStorage can only be obtained from the window opened in this window)

2. The data stored through sessionStorage will become invalid as soon as the browser window is closed.

4. Clear a certain data stored through sessionStorage through sessionStorage.removeItem(key)

5. Clear all data stored in sessionStorage through sessionStorage.clear()

3.cookie

1. Store data through document.cookie = ' ';

2. Obtain data through document.cookie

Edit

3. Clear the data stored in cookies

4. Cookies have many attributes, including path, expiration time, Expires/Max-Age, and domain name.

1. path path

2. Expiration time Expires/Max-Age: Set the expiration time through Max-Age

 3. Expiration time Expires/Max-Age sets the expiration time through Expires

5. Characteristics of cookie storage

1. Storage size: about 4K

2. If the expiration time is not set, it will expire as soon as the window is closed. If it is set, it will expire as soon as the expiration time is set.

4. Cookie packaging

1. Encapsulation of cookie storage

2. Obtain the package of cookie storage data

5. Simple application of cookies

------------------------------------------------------------------------------------- 

Server stores cookie + session

1. The backend server stores cookies

1. Set cookies: ctx.cookies.set(key, value); 

 2. Get cookie ctx.cookie.get(key);

3. Multiple ajax requests on one page at the same time. Note: Whoever requests the back-end server to complete the request first will complete the request first.

4. Server cookie summary: (very important)

1. Storage location of back-end cookies: Cookies set by the back-end will be stored in the client browser, and cookies set by the front-end are also in the client browser, and are in the same location.

2. The cookies in the client browser (the cookies set by the front-end and back-end are both in the client browser) will appear in the request header. The reason is that every time a request is made, the cookies stored in the client will be sent to Server (whether it is a cookie set by the front end or a cookie set by the back end) --> Every time the front end initiates a request (as long as the request has a request header, it will carry the cookie and send it to the server)

3. Set cookies on the backend, and limit the normal storage and acquisition of transmission to the same origin (there are cookies in the request header). If you want to store and obtain normally in cross-domain situations, you need to set up to allow cross-domain storage of cookies. -->Cross-domain settings

4. The client browser saves the front-end and back-end cookies. Although it will be carried in the request header every time a request is made and then sent to the server, the back-end server cannot get it (ctx.cookies.get(key of the front-end cookie) )), only backend cookies can be obtained. Although the cookie set by the backend is saved in the client browser, it cannot be obtained by the frontend (document.cookie). Only the frontend cookie can be obtained.

2. Backend server stores session 

1.Set session ctx.session.Attribute name = 'value';

2. Get session ctx.session.property name

3. Like cookies, sessions can be set and obtained normally only if they are not cross-domain, and cannot be obtained if they are cross-domain.

 4. In the case of same origin: When the backend uses the session to store data, it will create a cookie (EGG_SESS), and this cookie will be automatically saved in the client browser.

  5. In the case of different sources: When the backend uses the session to store data, it will still create a cookie (EGG_SESS), but this cookie will not be saved in the client browser).

6. In the case of non-cross-domain: When the backend uses session to store data, a unique cookie (EGG_SESS) will be created. Then when the backend wants to obtain the stored session data, it must be based on the cookie created when using session to store data. This cookie value parses the corresponding session

7. If you want to achieve the effect of 6 in a cross-domain situation, you must configure cross-domain. Similar to cross-domain cookie configuration.

8. To store some important data, use session, because cookies will be exposed in the browser, and session obtains data through back-end decoding. No data is exposed to the browser.


client storage

Foreword: The data required by many homologous pages can be stored through cookies or localStorage or sessionStorage. But the data should not be too large because the client storage size is limited.

Same-origin policy: a security strategy for browsers

Same origin: If the protocol, IP, and port (the domain name can be considered to be a combination of IP and port) are the same, they are considered to be of the same origin.

eg: Baidu default port number 443

Client-side storage is limited to the same origin: As long as it is from the same origin, using cookies or localStorage or sessionStorage to store data on this page can also be used in other pages.

1.localStorage

1. Store data through localStorage.setItem(key, value)

localStorage.setItem(key,value); Store in the form of key-value pairs

localStorage.setItem('stuname','蓝色天空');
localStorage.setItem('stuage',22);

2. Characteristics of localStorage storage

1. Store data through localStorage and save it permanently as long as it is not cleared.

2. Storage size: about 5M

3. Get the stored data through localStorage.getItem(key)

console.log(localStorage.getItem('stuage'));
console.log(localStorage.getItem('stuname'));

4. Clear a certain data stored in localStorage through localStorage.removeItem(key)

This method only clears the data stored in a certain localStorage

5. Clear all data stored in localStorage through localStorage.clear()

This method clears all data stored through localStorage

2.sessionStorage

1. Store data through sessionStorage .setItem(key, value)

    <body>
        <a href="./客户端存储数据的获取.html">跳到</a>
        <h1>存储数据</h1>
        <script>
           sessionStorage.setItem('flower','红玫瑰');
           sessionStorage.setItem('age',22);
        </script>
    </body>

2. Get the stored data through sessionStorage.getItem(key)

console.log(sessionStorage.getItem('flower'));
console.log(sessionStorage.getItem('age'));

3. Features of sessionStorage storage

1. sessionStorage is not only limited to the same source, but also to the same window ( the data stored in sessionStorage can only be obtained from the window opened in this window )

eg: On the storage data window page, click the hyperlink to jump to the customer storage data acquisition window page. If it is from the same source or from the window opened in this window, the data stored in this window through sessionStorage can be obtained.

If you directly open the client storage data acquisition window page, you will not be able to get the data stored through sessionStorage in the storage data window page.

2. The data stored through sessionStorage will become invalid as soon as the browser window is closed.

4. Clear a certain data stored through sessionStorage through sessionStorage .removeItem(key)

This method only clears the data stored in a certain sessionStorage

5. Clear all data stored in sessionStorage through sessionStorage .clear()

This method clears all data stored through sessionStorage

3.cookie

1. Store data through document.cookie = ' ';

            document.cookie = 'beauty = 宋花花';
            document.cookie = 'age = 22';

2. Obtain data through document.cookie

//存储
document.cookie = `stuage=21`;
document.cookie = `stuname1=red`;
//获取
console.log(document.cookie);

3. Clear the data stored in cookies

Generally, there is no need to clear data for cookies, because it will be automatically cleared once its expiration time is up. If you want it to be cleared immediately, you can set its expiration time to 0.

document.cookie = `stuname1=red;max-age=${0};path=/`;

Or delete it directly in the browser. 

4. Cookies have many attributes, including path, expiration time, Expires/Max-Age, and domain name.

1. path path

If the path is not specified, it defaults to the folder where the html file where the cookie stores data is located . That is, only files in that folder can access the data stored in the cookie. Files not in that folder cannot.

Therefore, the path attribute value is generally set to the root directory of the entire project, so that files in the entire root directory can access the value stored in the cookie.

document.cookie = `stuname1 = 100;path=/`;

Analysis: path=/ means setting the path to the root directory of the entire project. Other files under this project can also access the data stored in the cookie.

2. Expiration time Expires/Max-Age: Set the expiration time through Max-Age

If the expiration time is not specified: the default is Session, which means that the window disappears as soon as it is closed (other files in the directory where the file is located cannot access the value stored in the cookie)

Specify expiration time: Note: this unit is seconds, not milliseconds

eg: Expires after 7 days (max-age is usually written in front of the path)

 document.cookie = `stuname1 = 100;max-age=${7*24*60*60};path=/`;

 Analysis: Setup successful.

question:

Question: If the Domain, Path, and Max-Age are all the same, will the cookie store two data named stuname1 if it is set twice?

//域名,path,max-age 都相同
document.cookie = `stuname1=blue`;
document.cookie = `stuname1=red`;

result:

 Analysis: It is equivalent to setting the same attribute, and the latter will override the former.

 3. Expiration time Expires/Max-Age sets the expiration time through Expires

Note: If you set the expiration time through Expires, the unit is not seconds. It is a format that Expires can recognize and you need to set it manually.

        <script>
            //存储
            let tim = new Date(); //得到是现在的时间
            tim.getTime();        //拿到当前的时间戳  毫秒值
            // tim.getTime()+7*24*60*60*1000  //未来7天   这是未来7天的时间戳
            tim.setTime(tim.getTime()+7*24*60*60*1000);//传一个时间戳,就可以把传入的时间戳转成对应的时间
            console.log(tim); //这个时候打印 tim 就不是当前的时间了而是未来7天的时间
            //然后转换为 Expires 可以识别的时间格式  调用toGMTString方法
            document.cookie = `stuname1=red;expires=${tim.toGMTString()};path=/`;
        </script>

5. Characteristics of cookie storage

1. Storage size: about 4K

2. If the expiration time is not set, it will expire as soon as the window is closed. If it is set, it will expire as soon as the expiration time is set.

4. Cookie packaging

1. Encapsulation of cookie storage

    <script>
        function setCookie(key, value, day) {
            document.cookie = `${key}=${value};max-age=${day*24*60*60};path=/`;
            //针对于 Expires
            // let tim = new Date();
            // tim.getTime();
            // tim.setTime(tim.getTime() + day * 24 * 60 * 60 * 1000);
            // document.cookie = `${key}=${value};expires=${tim.toGMTString()};path=/`; 
        }
        //setCookie(key,value,day); //这里day表示天数
        setCookie('stuage', '21', 7);
        setCookie('stuname','宋花花',7);
        setCookie('num',200,7);
    </script>

Get the stored data, the result is:

console.log(document.cookie); //'num=200; stuage=21; stuname=宋花花'

Analysis: All the data stored in the cookie will be put into a string and printed out.

2. Obtain the package of cookie storage data

Analysis: What you get through document.cookie is all the data saved through cookies, but if you just want to get a certain data saved through cookies, it is not possible. The function encapsulated here can be achieved.

    <script>
        function getCookie(key){
            let allCookie = document.cookie;          //'num=200; stuage=21; stuname=宋花花'
            let allCookieArr = allCookie.split('; '); //['num=200', 'stuage=21', 'stuname=宋花花']
            for(let i=0;i<allCookieArr.length;i++){
                if(allCookieArr[i].includes(key)){
                    return allCookieArr[i].split('=')[1]; //['stuname','宋花花']
                }
            }
            return null;                 
        }   
        console.log(getCookie('stuname')); //宋花花
    </script>

5. Simple application of cookies

By setting the expiration time through cookies, you can set to determine the user's login status. If it expires, you need to log in again.

Login: login page

<body>
    <form>
        <!-- 手机号11位数 -->
        账号: <input type="text" name="account">
        <br>
        <!-- 6-12位 -->
        密码: <input type="password" name="pwd">
        <br>
        <input type="button" value="登录" id="loginBtn">
    </form>
    <script>
        let loginBtn = document.querySelector('#loginBtn');
        let account = document.querySelector('input[name="account"]');
        let pwd = document.querySelector('input[name="pwd"]');
        loginBtn.onclick = function () {
            //判断账号和密码是否满足格式--正则(前端)
            let reg = /^1[3-9]\d{9}$/ig;
            if (!reg.test(account.value)) {
                alert('账号输入的手机格式不对,请重新输入');
                return;
            }
            if (pwd.value.length < 6 || pwd.value.length > 12) {
                alert('密码格式不对,请输入6-12位的密码');
                return;
            }
            //把账号和密码存入到cookie里面,设置过期时间,可以判断用户的登录状态,如果过期了就需要重新登录
            function setCookie(key, value, day) {
                document.cookie = `${key}=${value};max-age=${day*24*60*60};path=/`;
            }
            //setCookie(key,value,day); //这里day表示天数
            setCookie('account',account.value, 7);
            setCookie('pwd',pwd.value, 7);
            window.location.href = './stuname.html';
        }
    </script>
</body>

Student details page:

<body>
    <h1>学生详情页</h1>
    <script>
        function getCookie(key){
            let allCookie = document.cookie;         
            let allCookieArr = allCookie.split('; '); 
            for(let i=0;i<allCookieArr.length;i++){
                if(allCookieArr[i].includes(key)){
                    return allCookieArr[i].split('=')[1]; 
                }
            }
            return null;                 
        }
        //判断用户是否处于登录状态,就是看cookie保存的账号和密码过期没有,过期了就要回到登录页面重新登录 
        if(!getCookie('account')){
            window.location.href = './login.html';
        }else{
            console.log(getCookie('account'));
        }
        
         
    </script>
</body>

------------------------------------------------------------------------------------- 

Server stores cookie + session

Cookies and sessions explained based on egg:

Official website address: Cookie and Session - Egg (eggjs.org)

1. The backend server stores cookies

1. Set cookies: ctx.cookies.set(key, value)

 ctx.cookies.set('num1',100);
 ctx.cookies.set('num2',200);

The front-end uses the axios framework to make Ajax requests for cookies set by the back-end. You can find the cookies set by the back-end server in the response header corresponding to the browser console (the interface for setting the back-end cookie).

 2. Get cookie  ctx.cookie.get(key);

3. Multiple ajax requests on one page at the same time. Note: Whoever requests the back-end server to complete the request first will complete the request first .

Ajax requests are asynchronous . A page may initiate multiple ajax requests at the same time . However, the ajax request does not mean whichever one is written first will be executed first . But when a page initiates an ajax request at the same time, multiple ajax requests are initiated at the same time. Whoever requests the back-end server to complete the request first will complete the request first .

When a page initiates multiple ajax requests at the same time, it is uncertain which ajax request is completed first, because the routing of each ajax request has different functions and the time it takes is different .

 Question: What should I do if I want to obtain the cookie set by the backend after the request is completed?
so:

    <script>
        axios.get(`http://127.0.0.1:7001/setcookie`)
            .then(function (response) {
                //请求后端接口成功就会执行,请求成功后的数据放在response里面
                console.log('cookie设置成功:', response);
            })
            .catch(function (error) {
                console.log(error);
            })

        axios.get(`http://127.0.0.1:7001/getcookie`)
            .then(function (response) {
                console.log('cookie获取成功:', response);
            })
            .catch(function (error) {
                console.log(error);
            })
    </script>

Analysis: This is initiating two ajax requests at the same time. There is no guarantee which one will be executed first, so the above is not possible.

    <script>
        axios.get(`http://127.0.0.1:7001/setcookie`)
            .then(function (response) {
                console.log('cookie设置成功:', response);
                //请求完成,并成功  cookie设置完成  才进行取 cookie
                axios.get(`http://127.0.0.1:7001/getcookie`)
                    .then(function (response) {
                        console.log('cookie获取成功:', response);
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
            })
            .catch(function (error) {
                console.log(error);
            })
    </script>

Analysis: Only in this way can we ensure that the back-end cookies are set up before they can be obtained.

4. Server cookie summary: (very important)

cookie:设置cookie:ctx.cookies.set(key,value)

            Get cookies: ctx.cookie.get(key) 

1. Storage location of back-end cookies: Cookies set by the back-end will be stored in the client browser, and cookies set by the front-end are also in the client browser, and are in the same location.

2. The cookies in the client browser (the cookies set by the front-end and back-end are both in the client browser) will appear in the request header. The reason is that every time a request is made, the cookies stored in the client will be sent to Server (whether it is a cookie set by the front end or a cookie set by the back end) --> Every time the front end initiates a request (as long as the request has a request header, it will carry the cookie and send it to the server)

Analysis: Cookies will appear in the request header only if they are from the same source, and cookies will not appear in the request header if they are from different sources. If different sources also want cookies to appear in request headers, they must configure cookies across domains.

3. Set cookies on the backend, and limit the normal storage and acquisition of transmission to the same origin (there are cookies in the request header). If you want to store and obtain normally in cross-domain situations, you need to set up to allow cross-domain storage of cookies.  -->Cross-domain settings

01. In the case of the same origin, the back-end cookie stored in the browser can be obtained by sending an ajax request through the back-end code ctx.cookie.get(key).

Front-end code:

    <script>
        axios.get(`http://127.0.0.1:7001/setcookie`)
            .then(function (response) {
                console.log('cookie设置成功:', response);
                //请求完成,并成功  cookie设置完成  才进行取 cookie
                axios.get(`http://127.0.0.1:7001/getcookie`)
                    .then(function (response) {
                        console.log('cookie获取成功:', response);
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
            })
            .catch(function (error) {
                console.log(error);
            })
    </script>

Backend code:

 Front-end results:

02. In the case of different sources, the back-end cookie stored in the browser cannot be obtained by sending an ajax request and then obtaining it through the back-end code ctx.cookie.get(key).

03. If it is not from the same origin, and you want to send the back-end cookie stored in the browser by sending an ajax request, and then obtain it through the back-end code ctx.cookie.get(key) , you must perform cross-domain configuration:

The backend egg needs to be set:

  //配置cors:在 config/config.default.js
  // 跨域的配置
  config.cors = {
    // origin: '*', //允许的域,*代表所有的
    //origin: 'http:127.0.0.1:80', //如果想携带cookie,这里必须指定ip和端口号
    origin: 'http:127.0.0.1',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', //允许跨域的请求方法
    credentials:true //后端允许跨域携带cookie
  };

Analysis: origin: 'http:127.0.0.1:80' If the port number 80 is written here, the port number 80 must also be written in the browser address bar. Even if it can be omitted, 80 must be added, otherwise it will be cross-domain. But it is best not to write 80, because 80 is the default port of apache, and the browser will automatically omit 80, and 80 is written here again, but the cross-domain requirements are very strict and must be the same as the configuration, even if it can be omitted, so It is best not to write 80 (because if you do, the browser will also write 80, but it will be automatically omitted, which is different from here, and it will report cross-domain)

The front end also needs to be set: if it is a get request :

//表示跨域请求时是否需要使用凭证(cookie)
//withCredentials: true  表示需要
axios.get(url,{params:dataObj, withCredentials: true })

Analysis: Not required by default, it is fasle. If cross-domain cookie transmission is required, it is true. Both request setting and back-end cookie acquisition must be set :

            axios.get(`http://127.0.0.1:7001/setcookie`, {
                withCredentials: true
            })
            .then(function (response) {
                console.log('cookie设置成功:', response);
                //请求完成,并成功  cookie设置完成  才进行取 cookie
                axios.get(`http://127.0.0.1:7001/getcookie`, {
                        withCredentials: true
                    })
                    .then(function (response) {
                        console.log('cookie获取成功:', response);
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
            })
            .catch(function (error) {
                console.log(error);
            })

 The front end also needs to be set: if it is a post request:

axios.post(url,dataObj,{withCredentials: true })

 axios.post('http://127.0.0.1:8000/login', {
            //给后端传递的数据
            account: account,
            pwd: pwd
        },{withCredentials: true })
        .then(function (response) {
            //请求后端成功后,后端返回给前端的数据:response
            console.log(response);
            alert(response.data.data);
            if (response.data.data == '登录成功') {
                //账号和密码正确就跳转到student.html
                window.location.href = './students.html';
            }
        })
        .catch(function(error){
            //请求后端失败了,失败原因在error
            console.log('请求后端失败了,失败原因为:',error);
        })

result:

4. The client browser saves the front-end and back-end cookies. Although it will be carried in the request header every time a request is made and then sent to the server, the back-end server cannot get it (ctx.cookies.get(key of the front-end cookie) )), only backend cookies can be obtained. Although the cookie set by the backend is saved in the client browser, it cannot be obtained by the frontend (document.cookie). Only the frontend cookie can be obtained.

2. Backend server stores session 

1.Set session  ctx.session.Attribute name = 'value';

  async setsession() {
    const {ctx} = this;
    ctx.session.id = 101;
    ctx.session.account = '18996883123';
    ctx.body = 'session设置成功';
  }

2. Get session ctx.session.property name

  async getsession() {
    const {ctx} = this;
    let id = ctx.session.id;
    let account = ctx.session.account;
    ctx.body = {
      id,account
    };
  }

3. Like cookies, sessions can be set and obtained normally only if they are not cross-domain, and cannot be obtained if they are cross-domain.

In the case of the same origin: both the front-end and back-end codes are in egg.

In the case of different sources: the front-end code is in apache and the back-end code is in egg

 4. In the case of same origin: When the backend uses the session to store data, it will create a cookie (EGG_SESS), and this cookie will be automatically saved in the client browser.

  5. In the case of different sources: When the backend uses the session to store data, it will still create a cookie (EGG_SESS), but this cookie will not be saved in the client browser).

 

 

6. In the case of non-cross-domain: When the backend uses the session to store data, a unique cookie (EGG_SESS) will be created, and then when the backend (not the interface that sets the session, other backend interfaces) wants to obtain the stored session data , the corresponding session must be parsed based on the cookie value created when using the session to store data.

Analysis: When the backend saves data through the session, it will automatically generate a cookie (EGG_SESS) and save it to the front-end browser. Then when the data in the session needs to be retrieved, the front-end will put the generated cookie (EGG_SESS) in the request header. Passed to the backend, the backend parses the data saved in the session based on this cookie value.

7. If you want to achieve the effect of 6 in a cross-domain situation, you must configure cross-domain. Similar to cross-domain cookie configuration.

The backend egg needs to be set:

  //配置cors:在 config/config.default.js
  // 跨域的配置
  config.cors = {
    // origin: '*', //允许的域,*代表所有的
    //origin: 'http:127.0.0.1:80', //如果想携带cookie,这里必须指定ip和端口号
    origin: 'http:127.0.0.1',
    allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH', //允许跨域的请求方法
    credentials:true //后端允许跨域携带cookie
  };

The front end also needs to be set: if it is a get request :

//表示跨域请求时是否需要使用凭证(cookie)
//withCredentials: true  表示需要
axios.get(url,{params:dataObj, withCredentials: true })
    <script>
        axios.get(`http://127.0.0.1:7001/setsession`, {
                withCredentials: true
            })
            .then(function (response) {
                console.log('setsession设置成功:', response);
                //请求完成,并成功  cookie设置完成  才进行取 cookie
                axios.get(`http://127.0.0.1:7001/getsession`, {
                        withCredentials: true
                    })
                    .then(function (response) {
                        console.log('getsession获取成功:', response);
                    })
                    .catch(function (error) {
                        console.log(error);
                    })
            })
            .catch(function (error) {
                console.log(error);
            })
    </script>

 The front end also needs to be set: if it is a post request:

axios.post(url,dataObj,{withCredentials: true })

result:

8. To store some important data, use session, because cookies will be exposed in the browser, and session obtains data through back-end decoding. No data is exposed to the browser.

9. There is only one cookie generated by session storage in a client browser.

eg: When your backend writes the login interface, you need to use the session to store data. The corresponding front-end will generate a cookie value ( cookie (EGG_SESS)). Then when your backend writes the registration interface, you need to use the session to store data. At this time, the front end will not generate a new cookie value ( cookie (EGG_SESS)). A client browser only has one cookie ( cookie (EGG_SESS)) created through the session , but the data in ( cookie (EGG_SESS)) will be changed due to the session. The storage is different and will be updated, but the entire client browser has only one cookie created through the session ( cookie (EGG_SESS))

10.Session has default configuration (including expiration time) + delete session

In the Egg framework config.default.js file

exports.session = {
  key: 'EGG_SESS',
  maxAge: 24 * 3600 * 1000, // 默认是1 天
  httpOnly: true,
  encrypt: true,
};

You can also set the session expiration time in the code (but it is not recommended)

//设置session得过期时间(1分钟后过期)
ctx.session.maxAge = 60*1000;

If you want to delete the session, directly assign it to null

ctx.session = null;

3. Application of data storage--judgment of login status

Guess you like

Origin blog.csdn.net/weixin_47075145/article/details/126472245