Why cache?

When we visit a server, if the server needs to respond to resources every time, then the server will be very stressed, and the browser will be very slow to load resources every time the server responds. Caching is important for both browsers and clients.

Advantages of browser caching

1. Reduce unnecessary data transfer

2. Reduce the burden on the server and improve the performance of the website

3. Accelerate the browser loading speed to improve user experience

Strong cache

When the browser requests a server’s data, The server can add cache-Control (HTTP1.1) or Expires (http1.0) fields in the response header to configure strong caching. The browser will cache the requested resource to the local disk based on the configuration And it returns 200 status codes but in general

Max-age =3000 Cache validity period 3000 seconds

Public can be cached by browsers and proxy servers

Private can only be cached by the browser

Immutable Prevents HTTP requests to the server when refreshing the browser

No-cache Does not set strong cache (usually negotiated cache is used when strong cache expires)

No-store does not set any cache strong cache and negotiation cache

Negotiate the cache

Strong cache cache is server caching strategy and negotiation When a browser sends a request for the first time the client will respond resources and a resource identifier And the resource local cache When the browser to access the server again This resource identifier will be carrying the client will compare the logo If the logo is the same Not updated resources return a status code 304 The browser receives the 304 status code and accesses the cache directly. If the identity is different, it returns the 200 status code and responds to the browser with the latest resource and resource identity

Resource identification type

Last-Modified

Records the latest update time of server resources

The response header field last-Modified

Request the header field if-modified-since

ETag

A unique string that records a server resource

The response header field ETag

Request header field if-none-match

Difference between Last-Modified and ETag

Last-modified record is a time mark in seconds. However, updating resources with high density results in less accuracy. Resources sometimes need to be updated periodically (only the update time is changed, ETag is slightly less efficient than last-Modified ETag because it computs a hash value each time the resource identifier is generated Last-modified just takes the current system time

Nodejs sets negotiation strong cache and negotiation cache

Res.setheader ('max-age': '3600 public') // cache res.setheader (etag: '5C20ABBD-e2E8 ') // Negotiate cache etag res.setheader (' last-Modified ': Mon, 24 Dec 2018 09:49:49 GMT) // Negotiate cache last-mo______Copy the code