Speaking of front-end data storage, it has to mention Cookie, sessionStorage and localStorage, which is the most familiar front-end data storage words we contact, as a front-end development, front-end engineer, these three words have not used first, but you must know when learning. SessionStorage and localStorage also don’t know how to use them

Front-end data storage

As we all know, as a front-end developer, more or less in the development process due to a variety of requirements, need to store some data in the front-end, such as login authentication, may use cookies, or localStorage to store tokens, and then request manual bring. So it’s important to figure out what front-end storage means and how to use the words we’ve become familiar with (Cookie, sessionStorage, localStorage) 😝

The following is a comparison table of common front-end storage methods summarized by myself, which I understand so far. If there are any questions, please point out:

Cookie

HTTP cookies, often called cookies, were originally used on the client side to store session information. The standard requires the server to send a set-cookie HTTP header containing session information as part of the response to any HTTP request. ———————— JavaScript Advanced Programming

To put it bluntly, it is generally used for login authentication. After sending a login request, the server sets set-cookie in the response header returned and sets its value. In addition, cookies follow the same origin policy of the browser, and the cookies of the current page cannot be accessed from pages of different sources. If you can, you can get cookies and fake requests for XSS and CSRF attacks.

As shown in the figure above, we have set-cookie in the response header and Set the corresponding value returned by the server. When we look at the Cookie in the Application of the current page, we find that there is already the Cookie just returned. Session cookies are generally not stored in the hard disk, but in memory. If the expiration time is set, the browser will save the cookies to the hard disk.

Set-Cookie
The cookie is brought back to the server with the request sent by the page, and the server determines the value of the cookie to determine the current login status.

Ajax, Axios, and FETCH carry cookie cases

As we said earlier, as soon as the server sets the value of set-cookie in the response header, the server plants a Cookie in the browser. Each subsequent request carries the Cookie, but there are some cases where the request does not carry the Cookie by default.

Cors cross-domain requests and FETCH requests do not carry cookies by default

Ajax requests in jQuery

We don’t care about jSONP requests sent in jQuery, because jSONP is not strictly a case of sending requests and returning data from the back end. For now, we will only discuss the JSON request that is sent. In the same domain, we send the Ajax request ⬇️

$.ajax({
  type: 'post'.url: '/person/detail'.dataType: 'json'.data: {
    id: 1
  },
  success: function (res) {},
  error: function(e) {}})Copy the code

If we are requesting an interface in a different domain, we do not consider the case of the reverse proxy, because the reverse proxy is theoretically still the interface accessing the same domain. Here is how we use Cors to solve cross-domain problems ⬇️

$.ajax({
  type: 'post'.url: '/person/detail'.dataType: 'json'.data: {
    id: 1
  },
  xhrFields: {
    withCredentials: true // If Cors is working across domains, we need to add this attribute value because the domain of our interface is different from the domain of our page
  },
  success: function (res) {},
  error: function(e) {}})Copy the code

Axios request

The following is a request library that we often use in the Vue or React library — Axios. Axios sends Cors cross-domain requests and does not include cookies ⬇️ by default

axios({
  method: 'post'.url: '/person/detail'.data: {
    id: 1,}});Copy the code

The above is a normal domain request, now let’s see how to send Cors request

axios({
  method: 'post'.url: '/person/detail'.data: {
    id: 1,},withCredentials: true.// If we set this value, we can send the Cors request. This value is false by default
});
Copy the code

Fetch request

Fetch is a relatively low-level API provided by javascript, which makes it easy for us to initiate FETCH requests. However, FETCH request is only a low-level API now. Although it is more convenient than native Ajax requests, Ajax has been packaged by various libraries for easy use. Fetch pales in comparison. As far as we are concerned, fetch not only does not idle cookies when sending Cors requests, but by default, fetch will not send or receive any cookied from the server in any case. Let’s first look at normal requests ⬇️

fetch('/person/detail', {
  method: 'POST'.body: JSON.stringify({id: 1}),
  headers: {
    'content-type': 'application/json'}})Copy the code

Above we send a fetch request, then we need the request credentials, need to have a cookie how to do ⬇️

fetch('/person/detail', {
  method: 'POST'.body: JSON.stringify({id: 1}),
  credentials: 'include'.// Force a credential header with a cookie
  headers: {
    'content-type': 'application/json'}})Copy the code

Operating a cookie

After all, this chapter is about front-end data storage, and the above mentioned method of requesting cookie is only because the cookie will be carried back to the server with the request, so now we can see how to manipulate cookies, or get the value of cookies, but we generally don’t need to do that.

The format of the stored data

Here is the composition of a cookie from JavaScript Advanced Programming

  1. Name: The name of a uniquely identified cookie. Cookie names are case insensitive, so myCookie and myCookie are considered to be the same cookie. In practice, however, it is best to treat cookie names as case sensitive, as some servers treat cookies this way. The cookie name must be URL-encoded.
  2. Value: string value stored in cookie. The value must be URL-encoded.
  3. Domain: The domain for which the cookie is valid. This cookie information is included in all requests sent to the domain. This value may or may not include subdomains (such as www.wrox.com) (such as.wrox.com, which is valid for all subdomains of wrox.com). If not explicitly set, the field is considered to be from the field where the cookie was set.
  4. Path: Cookies should be sent to the server for that path in the specified domain. For example, you can specify the cookie can only access from http://www.wrox.com/books/, the www.wrox.com page won’t send a cookie information, even if the request is from the same domain.
  5. Expiration time: A timestamp indicating when the cookie should be deleted (that is, when it should stop sending this cookie to the server). By default, all cookies are deleted at the end of the browser session; But you can also set your own deletion time. This value is a DATE in GMT format (Wdy, DD-Mon-YYYY HH:MM:SS GMT) that specifies the exact time at which the cookie should be deleted. Therefore, cookies can remain on the user’s machine even after the browser is closed. If you set the invalid date to a previous time, the cookie will be deleted immediately.
  6. Security flag: When specified, cookies are sent to the server only when an SSL connection is used. For example, cookie messages can only be sent to https://www.wrox.com, while requests from www.wrox.com cannot send cookies. Each piece of information is part of the set-cookie header. Separate each piece with a semicolon (;) and a space, as shown in the following example.

Get cookies and change cookies

It’s really easy for us to get cookies from JS and just document. Cookie, we can get cookies from the current page.

Cookie obtained from the console above via document.cookie

We find that the cookie we get is a long string, and we see the serialized cookie in the Application. Now that we’ve got the cookie, all we have left to do is serialize ourselves, manipulate the string, and I won’t go into that.

If we change the cookie, it overwrites it if it has the same value, and creates a new one if it doesn’t

Through the above we can know how document.cookie obtains and changes the cookie value, no matter what the cookie saves, will be taken to the server with the request. If we need to manipulate the values of cookies frequently, we can encapsulate the get and set methods that manipulate cookies ourselves.


These are the cookies, after all, we should not use a lot of cookies to complete the front-end data storage work, one is the amount of storage is too small, the second is the request will take, waste bandwidth. Also because the request carries a cookie, there are interspersed dots that request to carry a cookie.


Web Storage

Web Storage overcomes some of the limitations of cookie generation. When data needs to be strictly controlled on the client, there is no need to continuously send data back to the server. Web Storage has two main purposes: 1. Provides a way to store session data in addition to cookies. 2. Provide a mechanism for storing large amounts of data that can exist across sessions.

Storage Api common to sessionStorage and localStorage

SessionStorage and localStorage both belong to Web Storage. Although their valid time is different, they have the same method for developers to use

// Clear method to delete all values in sessionStorage
sessionStorage.clear(); // Clear all sessionStorage data
localStorage.clear(); // Clear all data in localStorage

// getItem(name) retrieves the value based on the specified name
var name = sessionStorage.getItem('name'); // Get the value whose key is name
var name = localStorage.getItem('name'); // Get the value whose key is name
// Of course, we can get the value in storage differently, or we can get the value as follows
var name = sessionStorage.name; // Get the value whose key is name
var name = localStorage.name; // Get the value whose key is name

// key(index) retrieves the name of the value at index
var key = sessionStorage.key(0); // Get the first sessionStorage key, such as' name '
var key = localStorage.key(0); // Get the key of the first value in localStorage, such as' name '
// Get the first key, then we can get the corresponding value based on this key
var value = sessionStorage.getItem(key); // We get the first value of name
var value = localStorage.getItem(key); // We get the first value of name

// removedItem(name) Removes the key-value pair specified by name
sessionStorage.removedItem('name'); // Delete the value whose key is name
localStorage.removedItem('name'); // Delete the value whose key is name
// We can also delete objects using the delete method, which deletes attributes in the object
delete sessionStorage.name;
delete localStorage.name;

// setItem(name, value) sets a value for the specified name
sessionStorage.setItem('name'.'zhanwuzha'); // sessionStorage stores a name with the value zhanwuzha
localStorage.setItem('name'.'zhanwuzha'); // localStorage stores a name with the value zhanwuzha
// We can also use the other way to set it
sessionStorage.name = 'zhanwuzha'; // sessionStorage stores a name with the value zhanwuzha
localStorage.name = 'zhanwuzha'; // localStorage stores a name with the value zhanwuzha
Copy the code

The above is the method in Web Storage, covering the increase, deletion, change and check. The delete operator cannot delete data in WebKit, so we’ll use the removeItem() method instead;

Data stored in Web Storage will not be sent back to the server with the request, which is the biggest difference with cookie, and is a key value pair to save data, although cookie is also a key value pair, but is similar to ‘name= Zhanwuzha&age =16’ such a string, also need to be further processed.

sessionStorage

The sessionStorage object stores session-specific data, meaning that the data only lasts until the browser closes. This object, like a session cookie, also disappears when the browser closes. Data stored in sessionStorage can exist across page refreshes and, if the browser supports it, remain available after the browser crashes and restarts (Firefox and WebKit support it, IE does not). —————— JavaScript Advanced Programming

SessionStorage in addition to meeting the common methods of the above storage, its use is bound to a session:

  1. Following the same origin policy of the browser, different sources are not accessible at all
  2. The same session (even if the IP address is not the same session) complies with the same origin policy

Example:

name
zhanwuzha

The sessionStorage where we opened the new TAB still has the data we saved, but what if we typed the address directly into the address bar



New tabs opened by clicking on links (or using window.open) belong to the same session, but opening a new TAB always initializes a new session, even if the site is the same, they do not belong to the same session

When a page shares the same sessionStorage

localStorage

Compared to sessionStorage, localStorage is much easier to understand, as long as the data stored by the method mentioned above, without manual deletion, will always be retained, and as long as the same origin policy page, can share the same localStorage.

It’s easy to understand

indexedDB

what is indexedDB

IndexedDB is a browser-provided local database that can be created and manipulated by web scripts. We all know that cookies can store only 4 to 5kb of data, that Web Storage can store between 2.5 and 10mb (depending on the browser), and that indexedDB is generally no less than 250mb or no upper limit. It just feels like a really cool technology.

Not only has a large amount of storage space, but also supports the establishment of index, asynchronous, transaction and other real database existing functions

Here is ruan Yifeng’s blog about indexedDB. Ruan yifeng writes a detailed blog about indexedDB, with concepts and operations, and feels that such a technology might actually be used in the future, so you can check it out in advance

abandoned

Web SQL and globalStorage, which are not mentioned in this article, are largely obsolete, so they are not written

reference

  1. Introduction to IndexedDB for Browsers — Ruan Yifeng
  2. Will sessionStorage data be shared between multiple tabs on the same site? It depends on how tabs are opened.

Clocking off ~ May Day holiday ~


I’m a front end warrior, a front end elementary school. Bow down to the big boys.