preface

Back-end databases are commonly used for data storage, such as MySql and MongoDB. Caching technologies store data, such as Redis and Memcached.

Front-end data Storage is commonly used for cookies, Storage, and IndexedDB

Cookie

An HTTP Cookie (also known as a Web Cookie or browser Cookie) is a small piece of data that a server sends to a user’s browser and keeps locally. It is carried and sent to the server the next time the browser makes a request to the same server. Typically, it is used to tell the server whether two requests are from the same browser, such as to keep the user logged in. Cookies make it possible to record stable state information over stateless HTTP protocols.

classification

Cookie is always stored in the client (in early Java, Cookie is often compared with Session as a storage technology. Session stores data on the server, and a large amount of data storage will increase the burden on the server). It can be divided into memory cookies and hard disk cookies. The memory Cookie is maintained by the browser and stored in memory. After the browser closes, it disappears and its existence is short-lived. Hard disk Cookies are stored in hard disks and have an expiration date. They are not deleted unless manually deleted or the expiration date is reached. Therefore, according to the existence time, it can be divided into non-persistent cookies and persistent cookies.

Create a Cookie

Set-cookie response header and Cookie request header section The server uses the set-cookie response header to send Cookie information to the user agent (typically a browser). A simple Cookie might look like this: set-cookie: < Cookie name >=< Cookie value >

The server uses this header to tell the client to save the Cookie information

Gets cookies that are not HttpOnly tokens in the browser environment


var cookies = document.cookie;Copy the code



The disadvantage of the Cookie

Cookies are attached to every HTTP request, so they add traffic. Because cookies in HTTP requests are passed in plain text, security is problematic unless HTTPS is used.

Cookie size is limited to around 4KB, which is not sufficient for complex storage requirements.

Simple encapsulation of cookies

When setting cookies, the path and expiration time are set together. The expiration time must be converted to GMT or UTC

code

(function IIFE(root){
    function getCookie(cname, defaultValue){
        var value = new RegExp('(^ |; |) '+cname+'= (/ ^; *?) (; | $) '.'g').exec(document.cookie);
        console.log('value:', value);
        if(! value)return defaultValue;
        return value[2];
    }
    function setCookie(cname, cvalue, day, path){
        day = day || 1;
        path = path || '/';
        var date = new Date();
        date.setTime(date.getTime() + day * 24 * 60 * 60 * 1000);
        document.cookie = cname+'='+cvalue+'; expires=' + date.toGMTString() + '; path='+path+'; ';
    }
    function deleteCookie(cname){
        setCookie(cname, null, -1);
    }
    root.Util = {
        getCookie: getCookie,
        setCookie: setCookie,
        deleteCookie: deleteCookie,
    }
})(window);Copy the code

The test results



Storage

As an interface of the Web Storage API, a Storage provides the function of accessing session Storage or local Storage under a specific domain name. For example, you can add, modify, or delete data items from the Storage.

If you want to operate on the session storage of a domain name, use window.sessionStorage if you want to operate on the local storage of a domain name, use window.localStorage.

SessionStorage is used in the same way as localStorage, the difference is that sessionStorage will expire when the session is closed, that is, when the browser is closed, while localStorage will store data locally, it is not affected by closing the browser, unless manually cleared data

You can refer to the relevant API

Developer.mozilla.org/zh-CN/docs/…

code

(function IIFE() {if(! window.localStorage){ alert('your browser is not support localStorage! ');
        return;
    }
    function getStorage(sname, defaultValue){
        //result = window.localStorage.sname
        //result = window.localStorage[sname]
        var result = window.localStorage.getItem(sname);
        return result || defaultValue;
    }
    function setStorage(sname, svalue){
        window.localStorage.setItem(sname, svalue);
    }
    function removeItem(sname){
        window.localStorage.removeItem(sname);
    }
    function getKey(keyIndex){
        return window.localStorage.key(keyIndex);
    }
    function getAllKeys(){
        var arr = [];
        for(var i=0; i<window.localStorage.length; i++){ arr.push(window.localStorage.key(i)); }return arr;
    }
    function clearStorage(){
        window.localStorage.clear();
    }
    function onStorageChange(event){
        console.log(event)
    }
    window.addEventListener('storage', onStorageChange);
    window.Util = {
        getStorage: getStorage,
        setStorage: setStorage,
        removeItem: removeItem,
        getKey: getKey,
        getAllKeys: getAllKeys,
        clearStorage: clearStorage,
    }
})();Copy the code

The test results



IndexedDB

As the capabilities of the browser continue to increase, more and more sites are considering storing large amounts of data on the client side, which can reduce the amount of data retrieved from the server and bring it directly from the local.

Existing browser data storage schemes are not suitable for storing large amounts of data: cookies are less than 4KB in size, and each request is sent back to the server; LocalStorage is between 2.5MB and 10MB (depending on the browser), does not provide search, and cannot create custom indexes. So a new solution was needed, and this was the context in which IndexedDB was born.

In plain English, an IndexedDB is a browser-provided local database that can be created and manipulated by web scripts. IndexedDB allows you to store large amounts of data, provide a lookup interface, and build indexes. These are all things that LocalStorage does not have. In terms of database type, IndexedDB is not a relational database (it does not support SQL query statements) and is closer to a NoSQL database.

The IndexedDB API is available for reference

Wangdoc.com/javascript/…

code

(function IIFE() {if(! window.indexedDB){ alert('your browser is not support indexedDB! ');
        return;
    }
    var request = window.indexedDB.open('person', 1);
    var db;
    request.onerror = function (event) {
        console.log('Database opening error');
    };
    request.onsuccess = function (event) {
        db = request.result;
        console.log('Database opened successfully');
    };
    request.onupgradeneeded = function(event) {
        console.log('onupgradeneeded... ');
        db = event.target.result;
        var objectStore = db.createObjectStore('person', { keyPath: 'id' });
        objectStore.createIndex('name'.'name', { unique: false });
        objectStore.createIndex('email'.'email', { unique: true });
    }
    function add(obj) {
        var request = db.transaction(['person'].'readwrite')
            .objectStore('person')
            .add(obj)
            //.add({ id: 1, name: 'ccy', age: 18, email: '[email protected]' });

        request.onsuccess = function (event) {
            console.log('Data write success');
        };
        request.onerror = function (event) {
            console.log('Data write failure'); }}function read(index) {
        var transaction = db.transaction(['person']);
        var objectStore = transaction.objectStore('person');
        var request = objectStore.get(index);
        request.onerror = function(event) {
            console.log('Transaction failed');
        };

        request.onsuccess = function(event) {
            if (request.result) {
                console.log('Name: ' + request.result.name);
                console.log('Age: ' + request.result.age);
                console.log('Email: ' + request.result.email);
            } else {
                console.log('No data record obtained'); }}; }function readAll() {
        var objectStore = db.transaction('person').objectStore('person');
        objectStore.openCursor().onsuccess = function (event) {
            var cursor = event.target.result;
            if (cursor) {
                console.log('Id: ' + cursor.key);
                console.log('Name: ' + cursor.value.name);
                console.log('Age: ' + cursor.value.age);
                console.log('Email: ' + cursor.value.email);
                cursor.continue();
            } else {
                console.log('No more data! '); }}; }function update(obj) {
        var request = db.transaction(['person'].'readwrite')
            .objectStore('person')
            .put(obj)
            //.put({ id: 1, name: 'bill', age: 35, email: '[email protected]' });

        request.onsuccess = function (event) {
            console.log('Data updated successfully');
        };

        request.onerror = function (event) {
            console.log('Data update failed'); }}function remove(index) {
        var request = db.transaction(['person'].'readwrite')
            .objectStore('person')
            .delete(index);

        request.onsuccess = function (event) {
            console.log('Data deleted successfully');
        };
    }
    window.util = {
        add: add,
        read: read.readAll: readAll,
        update: update,
        remove: remove,
    }
})();Copy the code

The test results



Afterword.

Browser storage technology is currently popular on the above three basic introduction, webSql before the use of dialect SQLlite can not be unified, that is to say, this is an abandoned standard.

LocalStorage and indexedDB are not introduced in detail here, but are simply provided with sample codes for demonstration. If you are not familiar with them, please refer to the relevant API.

The resources

Developer.mozilla.org/zh-CN/docs/… Developer.mozilla.org/zh-CN/docs/… Zh.wikipedia.org/wiki/Cookie www.ruanyifeng.com/blog/2018/0… Wangdoc.com/javascript/…