Session

Since cookies can be tampered with by users and are not a secure option, sessions are used to address the need to prevent user tampering.

Session is a hash table that belongs to the server.

In use, define a session hash table and generate a random number as the current user’s sessionId. The use of random number is for security, so that users can not tamper with the correct sessionId of other users. Sessions [sessionId] is stored on the server, and the sessionId is sent to the browser via the Cookie.

The code implementation is as follows:

  let sessionId = Math.random() * 100000; // Change this to another random mode
  sessions[sessionId] = { sign_in_email: email };
  response.setHeader('Set-Cookie'.`sessionId=${sessionId}`);
Copy the code

By doing this, the browser doesn’t get user information directly. Instead, it gives a sessionId, and the server gets user information by matching sessions with the browser’s attached sessionId. Avoid users to obtain other users’ information by tampering with cookies. Moreover, the sessionId is randomly generated and there is no rule to follow, so it is impossible to forge other users’ sessionids.

  // Hash is the object of the information in the Cookie
  let mySession = sessions[hash.sessionId];
  let email;
  if (mySession) {
    email = mySession.sign_in_email;
  }
Copy the code

You can also get information about the current user, and the user can’t impersonate another user.

Association with cookies

  • The Session is to usesessionIdCookie based implementation
  • The Session is stored on the server and its Session ID is sent to the browser via cookies
  • The sessionId is sent to the server with the Cookie every time a request occurs

summary

  • sessionIdthroughCookieSend it to the browser
  • The browser wears this when accessing the serversessionId
  • The server has a block of memorysessionId– Key value pair hash table of user information (sessions)
  • So throughsessionIdYou can get information about the corresponding user

Sessions take up too much memory, each user needs to store (sessionId – user information), and cannot be reclaimed. When there are a large number of users, the hardware performance requirements are particularly high.

LocalStorage

LocalStorage is a hash table stored in the browser and can only hold strings (.toString() for non-strings).

The browser has an API for window.localstorage as follows:

Because the value of LocalStorage does not change with page closing, refreshing, etc., it can be used to store some values that do not need to change with page refreshing, and persistent storage.

Common scenarios are as follows: Record whether the user is prompted for certain information (cannot be used to record passwords)

The characteristics of

  • LocalStorage is independent of HTTP
  • The HTTP request does not carry the value of LocalStorage
  • Only pages with the same domain name can read LocalStorage from each other (less strict than the same-origin policy)
  • The maximum storage capacity of LocalStorage for each domain name is about 5Mb (varies by browser)
  • LocalStorage is permanently valid unless manually cleared by the user

.setItem()

This is used to store LocalStorage data and is used as follows

  / / grammar
  localStorage.setItem('key'.'value')

  / / instance
  localStorage.setItem('name'.'yyzcl')
Copy the code

Non-string keys and values are converted to strings and can be stored in JSON.

  localStorage.setItem('yyzcl', {age: '18'})

  localStorage.setItem('yyzcl2'.JSON.stringify({age: '18'}))
Copy the code

getItem()

LocalStorage = LocalStorage;

  / / grammar
  localStorage.getItem('key')

  / / instance
  localStorage.getItem('yyzcl2')
Copy the code

.removeItem

Delete a value that is already stored in LocalStorage.

  / / grammar
  localStorage.removeItem('key')

  / / instance
  localStorage.removeItem('yyzcl')
Copy the code

.clear()

Clear the value of LocalStorage.

Relationship with cookies

  • Cookies are sent to the server with HTTP requests, but LocalStorage is not
  • Cookie size is typically 4KB and LocalStorage size is typically 5Mb (varies by browser)
  • Cookies have a self-definable validity period and LocalStorage is always valid unless manually cleared by the user

SessionStorage

SessionStorage and LocalStorage similar, also has LocalStorage those API features. However, SessionStorage expires when the user closes the page (terminating the session)

HTTP cache

When we refresh the page, it consumes too much network and time to request the same resource all over again. Is there a way for HTTP to request the same resource directly from memory or hard disk, without going over the network connection server? There are several ways to do this.

Cache-Control

The cache-control generic header is used to implement caching mechanisms by specifying directives in HTTP requests and responses. Usage:

  / / grammar
  Cache-Control: max-age=<seconds>Responsetheader (' cache-control ', 'max-age=30'); response.setHeader(' cache-control ', 'max-age=30');Copy the code

If we cache-control the response to a page’s JS file and request it repeatedly within 30 seconds, the browser will block the request and instead read the JS file from memory or disk.

This is the first load.

In addition, there will be a cache-control: max-age=30 message in the response body, as shown in the following figure.

When the browser requests the JavaScript file again within 30 seconds, it looks like this.

As you can see from the graph, when cache-control is set and the same file is repeatedly requested within the valid time, the processing time is 0ms, meaning that the browser does not request the server at all, but reads the requested file from memory.

The cache time of JS and CSS files is usually set to a large value, such as one year.

How about updating the JS and CSS files?

Here only need to change JS, CSS request URL, for example, add a query parameter. The effect is as follows:

Expires

Expires is also used to Control caching, and unlike cache-control, the Expires response header contains a date/time after which the response Expires. An invalid date, such as 0, represents a past date, meaning that the resource has expired. Usage:

  / / grammar
  Expires: <http-date>// Instance Response.setheader ('Expires', 'Wen, 31 Jul 2018 15:55:10 GMT');Copy the code

Within the validity period, repeated requests are also blocked by the browser and the file is read from memory instead.

The URL of the same change request updates the file within the validity period.

It’s important to note that Expires returns the server time, and browsers use local time as a baseline for determining time. If the local time differs too much from the server time, the request can be buggy. For example, by setting the local time after the expiration date, each request is sent to the server without being blocked by the browser.

And when Expires is set with cache-control, Expires is ignored and only cache-control takes effect.

ETag

The ETag HTTP response header is the identifier for a specific version of the resource. This makes caching more efficient and saves bandwidth because the Web server does not need to send the full response if the content does not change. If content changes, using ETag helps prevent simultaneous updates of resources from overwriting each other (” midair collisions “).

ETag records the version number of the requested file. The browser will carry this version number (as the value of if-none-match) every time it requests the file. If the server finds that the version number of the file has not changed, the server will use the version number of the requested file. That is, the file has not changed, so there is no need to re-send the file to the browser and let the browser read the downloaded file in the cache.

You can use the MD5 value as the version number of the file, because even if a file sends only subtle changes, its MD5 value can change a lot.

ETag can be used as follows:

  / / grammar
  ETag: "<etag_value>"

  / / instance
  response.setHeader('ETag', fileMd5)
Copy the code

The results are shown below:

As you can see, although caching is utilized, the processing time is not 0ms compared to the previous two methods. This is because it did make a request to the server, but the server did not send the file to the browser after comparing the ETag values.

Last-Modified

Last-modified is a response header that contains the date and time when the resource identified by the source server was Modified.

Similar to ETag, an eigenvalue is set, and the server compares the eigenvalue to determine whether to allow the browser to cache, except that ETag uses the version number of the file, and last-Modified uses the time when the file was Last Modified. Usage:

  / / grammarLast-Modified: < dayname >, <day> <month> <year> <hour>:<minute>:<second> GMT // instance let lastModified = fs.statsync ('./ CSS /style.css', 'utf8').mtime.toGMTString(); response.setHeader('Last-Modified', lastModified);Copy the code

As long as the file has not changed, that is, the file modification time has not changed, the server will not send the file to the browser, and the browser will read the cache instead.

Like ETag, it makes a request, but the server does not return a file.